LeetCode:分割回文串(Python版本)
2019-03-25 20:59
369 查看
LeetCode刷题日记
分割回文串
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: “aab”
输出:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]
Python代码
class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """ if len(s) == 0: return [] else: res = [] self.dividedAndsel(s, [], res) return res def dividedAndsel(self, s, tmp, res): if len(s) == 0: res.append(tmp) for i in range(1, len(s)+1): if s[:i] == s[:i][::-1]: self.dividedAndsel(s[i:], tmp + [s[:i]], res)
代码分析
此题采用了回溯+递归的思路,先将字符串分割,再留下满足题目要求的字符串。
- 第一步分割
Eg: ['a','a','b'] ==> ['a','a','b'],['a','ab'],['aa','b'],['aab']
第二步找出符合条件的字符串['a','a','b'],['aa','b']
那么现在从程序输入开始分析:
s=['a','a','b'], len(s) != 0,之后调用
dividedAndsel('aab', [], [])
为了方便分析,用伪代码显示过程。
for i in range(1, len(s)+1): 此时 i = 1, len(s)+1 = 4,因此i 可取,1,2,3 s[:i] = 'a' s[i:] = 'ab' tmp + [s[:i]] = ['a'] 第一次递归 for i in range(1, len(s)+1): 此时 i = 1, len(s)+1 = 3,因此i可取1,2 s[:i] = 'a' s[i:] = 'b' tmp + [s[:i]] = ['a',< 1d25c /span>'a'] 第三次递归 for i in range(1, len(s)+1): 此时 i = 1, len(s)+1 = 2,因此i可取1 s[:i] = 'b' s[i:] = '' tmp + [s[:i]] = ['a','a','b'] 第四次递归 for i in range(1, len(s)+1): 此时 无法进入for循环 因为len(s)+1 = 1 ...... 之后数i的变化,一层一层退就好了。
作为一个初学者,看懂这段代码真的挺吃力的,现在拿出来分析过程,希望学习的人能省点力。
相关文章推荐
- [和小菜鸡一起刷题(python)] LeetCode 131. 分割回文串 (Palindrome Partitioning)
- 利用python 完成 leetcode131 分割回文串
- 利用python 完成 leetcode132 分割回文串 II
- [和小菜鸡一起刷题(python)] LeetCode 132. 分割回文串 II (Palindrome Partitioning II)
- leetcode-最长回文串(python)
- LeetCode:回文数(Python版本)
- LeetCode:罗马数字转整数(Python版本)
- LeetCode 高级 - 分割回文串
- LeetCode 415. Add Strings(字符串相加)python3版本
- Leetcode:131. 分割回文串
- leetcode python 简单难度 解答版本(持续更新)
- LeetCode 278. 第一个错误的版本 Python
- leetcode131.分割回文串
- LeetCode-----回文串的最小分割
- 【LeetCode】Python实现-278. 第一个错误的版本
- LeetCode-Python-409. 最长回文串
- Python linux 上的管理工具 pyenv 安装, pip 使用, python项目(版本分割, 项目分割, 虚拟环境创建)
- leetcode:Palindrome Partitioning (字符串分割成回文串的所有方式) 【面试算法题】
- 【LeetCode】#131分割回文串(Palindrome Partitioning)
- LeetCode:盛最多水的容器(Python版本)