首页 > 代码库 > Leetcode 132. Palindrome Partitioning II
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。