[Leetcode][python]Palindrome Partitioning/Palindrome Partitioning II/分割回文串/分割回文串II

146 篇文章 4 订阅
145 篇文章 13 订阅

Palindrome Partitioning

DFS

代码

class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
if not s:
return [[]]
self.result = []
self.dfs(s, [])
return self.result

def dfs(self, s, temp):
if len(s) == 0:
self.result.append(temp)
for i in range(len(s)):
if self.isPalindrome(s[:i+1]):  # 前i个
self.dfs(s[i+1:], temp + [s[:i+1]])

def isPalindrome(self, cut):
return cut == cut[::-1]

Palindrome Partitioning II

代码

一

class Solution(object):
def minCut(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
dp = [i-1 for i in range(n+1)]
print dp
for i in range(1, n+1):
for j in range(i):
print s[j:i]
if s[j:i] == s[j:i][::-1]:
dp[i] = min(dp[i], dp[j]+1)
print 'youhuiwen', dp
print '---'

return dp[-1]



二

dp[i] = 0, 如果s[:i+1]是回文串
dp[i] = min(dp[i], dp[j-1]+1), 如果s[j:i+1]是回文串

class Solution(object):
def minCut(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
dp = [0 for __ in range(n)]
isPal = [[False for __ in range(n)] for __ in range(n)] # 是否回文存储矩阵
for i in range(n):
m = i
for j in range(i + 1):  # j在左边开始，i右边
if s[j] == s[i] and (j + 1 > i - 1 or isPal[j + 1][i - 1]):  # 如果i和j都不相等，不需要去判断是否是回文
isPal[j][i] = True
if j == 0:  # 整个都是回文串
m = 0
else:
m = min(m, dp[j - 1] + 1)  # 要么每个字母都拆，要么之前的字母拆了后+1
dp[i] = m
# for line in isPal:
#     print line
# print dp
return dp[-1]



总结

• 1
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
05-16 526

“相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。