题目: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.
给定一个字符串s,将s分割成一些子串,使每个子串都是回文串。
返回符合要求的最少分割次数。
回文串:正读和反读都一样的字符串
示例:
输入:"aab"
输出:1
解释:进行一次分割就可将s分割成["aa", "b"]
class Solution(object):
def minCut(self, s):
"""
:param s: str
:return: int
"""
l = len(s)
dpPart = [[False] * l for _ in range(l)]
dp = [i for i in range(l)]
# 判断回文串,填充dpPart
# 枚举字串长度
for length in range(l):
# 枚举子串开始位置,length==0表示子串长度为1
for i in range(l):
j = i + length
if j >= l:
break
if length == 0:
dpPart[i][j] = True
elif length == 1:
dpPart[i][j] = (s[i] == s[j])
else:
dpPart[i][j] = dpPart[i + 1][j - 1] and (s[i] == s[j])
# 填充dp
for i in range(1, l):
if dpPart[0][i]:
dp[i] = 0
continue
for j in range(1, i + 1):
# 枚举以s[i]结尾的回文串
if (dpPart[j][i]):
dp[i] = min(dp[i], dp[j - 1] + 1)
return dp[l - 1]
if __name__ == '__main__':
result = Solution()
count = result.minCut("aab")
print(count)
# 1