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

 

posted @ 2016-11-20 15:07  lettuan  阅读(179)  评论(0编辑  收藏  举报