[Lintcode]108. Palindrome Partitioning II /[Leetcode]132. Palindrome Partitioning II
108. Palindrome Partitioning II / 132. Palindrome Partitioning II
- 本题难度: Medium/Hard
- Topic: DP
Description
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example:
Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
我的代码
- 使用DFS超时
import collections
class Solution:
"""
@param s: A string
@return: An integer
"""
#min BFS
def minCut(self, s):
# write your code here
f = 0
q = collections.deque([[s,f]])
while q:
[tmps, f] = q.popleft()
if self.isValid(tmps):
return f
else:
for i in range(len(tmps),0,-1):
if self.isValid(tmps[:i]):
q.append([tmps[i:],f+1])
return 0
def isValid(self, s):
return s==s[::-1]
# l = len(s)
# for i in range(l//2):
# if s[i]!=s[l-1-i]:
# return False
# return True
别人的代码
DP
def minCut(self, s):
cut = [x for x in range(-1,len(s))]
for i in range(0,len(s)):
for j in range(i,len(s)):
if s[i:j] == s[j:i:-1]:
cut[j+1] = min(cut[j+1],cut[i]+1)
return cut[-1]
思路
我的思路:
最短->bfs
DP思路:
某一点,最短距离等于前面的+最后一个到他的回文。