Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s ="aab",
Return
[
["aa","b"],
["a","a","b"]
]
def dfs(S, path, res):
if len(S) < 1:
res.append(path[:])
return
i = 0
while i < len(S):
begin = 0
end = i
while begin < end:
if S[begin] == S[end]:
begin += 1
end -= 1
else:
break
if begin >= end:
path.append(S[0:i+1])
dfs(S[i+1:],path,res)
path.pop()
i = i + 1
def partition(S):
res = []
path = []
dfs(S, path, res)
return res
print partition("aba")
本文介绍了一种递归算法,用于将输入字符串分割成多个子串,确保每个子串都是回文串。通过深度优先搜索(DFS)遍历所有可能的分割方式,并使用双指针技巧来检查子串是否为回文。
122

被折叠的 条评论
为什么被折叠?



