这道题可以用dp来解决。对任意一条字符串,遍历其可能被分割的每个位置,检查分割点后面是否是回文串,而创建列表存储分割点前面子串所有可能的分割。
代码中dp[i]存储的即为s[0:i] 所有的回文分割字符串。所以对于新的位置i,遍历0~i-1之间的每一个位置j,如果s[j:i] 为回文串,则把dp[j]存储的所有分割与s[j:i]连接并append到dp[i]中,这样就得到了s[0:i] 的所有分割。最后输出dp[-1]即可。
代码:
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
length=len(s)
# each position stores all palindrome substrings from s[0:i]
dp = [[] for i in range(length+1)]
for i in range(1, length+1):
for j in range(i):
if self.ispalindrome(s[j:i]):
if len(dp[j])>0:
for pos in range(len(dp[j])):
dp[i].append(dp[j][pos] + [s[j:i]])
else:
dp[i].append([s[j:i]])
return dp[-1]
# whether a string is palindrome or not
def ispalindrome(self, s):
front, end = 0, len(s)-1
while front<=end:
if s[front]!=s[end]:
return False
front+=1
end-=1
return True