首页 > 其他 > 详细

Leetcode 132. Palindrome Partitioning II

时间:2016-11-20 15:51:37      阅读:210      评论:0      收藏:0      [点我收藏+]

求次数的问题一般用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

原文:http://www.cnblogs.com/lettuan/p/6082672.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!