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 '---'
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]