Leetcode 132. Palindrome Partitioning II

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 132. Palindrome Partitioning II相关的知识,希望对你有一定的参考价值。

求次数的问题一般用DP

 1 class Solution(object):
 2     def minCut(self, s):
 3         """
 4         :type s: str
 5         :rtype: int
 6         """
 7         n = len(s)
 8         maxInt = 2147483647
 9         cuts = [maxInt for x in range(n)]
10         p = self.palinTable(s)
11         for i in range(n):
12             temp = maxInt
13             if p[0][i] == True:
14                 cuts[i] = 0
15             else:
16                 for j in range(i):
17                     if p[j+1][i] and temp > cuts[j] + 1:
18                         temp = cuts[j] + 1
19                 cuts[i] = temp
20         return cuts[-1]
21                 
22     
23     
24     
25     def palinTable(self, s):
26         n = len(s)
27         
28         p = [[False for x in range(n)] for y in range(n)]
29         
30         for i in range(n):
31             p[i][i] = True
32             
33         for i in range(n-1):
34             if s[i] == s[i+1]:
35                 p[i][i+1] = True
36         
37         for curLen in range(3,n+1):
38             for i in range(n-curLen+1):
39                 j = i + curLen-1
40                 if s[i] == s[j] and p[i+1][j-1]:
41                     p[i][j] = True
42                     
43         return p

 

以上是关于Leetcode 132. Palindrome Partitioning II的主要内容,如果未能解决你的问题,请参考以下文章

132 Palindrome Partitioning II 分割回文串 II

132. Palindrome Partitioning II

132. Palindrome Partitioning II

132. Palindrome Partitioning II

132. Palindrome Partitioning II

131. 132. Palindrome Partitioning *HARD* -- 分割回文字符串