题目:分割回文串
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例 :
输入: "aab", 输出:
[ ["aa","b"],
["a","a","b"]]
---------------------------------------------------------------------
思路:正常的遍历思路肯定超时,可以考虑递归方法。
解法1:
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)
解法2:
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
if s == '':
return []
res = []
if s == s[::-1]:
res.append([s])
for i in range(len(s)):
if s[:i+1] == s[i::-1]:
par = self.partition(s[i+1:])
# print("p:", par)
for c in par:
# print("s[i + 1]:", s[i + 1:])
# print("c:", c)
if c != []:
res.append([s[:i+1]] + c)
return res
参考:
https://blog.youkuaiyun.com/l695290718/article/details/88805975
https://blog.youkuaiyun.com/qq_37369124/article/details/88083196
https://blog.youkuaiyun.com/wenqiwenqi123/article/details/80198059