132. Palindrome Partitioning II
Hard
191954Add to ListShare
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 1:
Input: s = "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
Example 2:
Input: s = "a"
Output: 0
Example 3:
Input: s = "ab"
Output: 1
Constraints:
1 <= s.length <= 2000
s
consists of lower-case English letters only.
参考详见:https://github.com/soulmachine/leetcode
class Solution:
def minCut(self, s: str) -> int:
"""
assert Solution().minCut("aab") == 1
assert Solution().minCut("a") == 0
"""
n = len(s)
# f[i] 表示i -> n-1 最小剪数
f = [0] * (n + 1)
# p[i][j] 是否是回文数
p = [[False for col in range(n)] for row in range(n)]
# 初始化f,极端条件如 “abc” 每位各不相同需要 len("abc")-1 次剪刀
for i in range(0, n + 1):
f[i] = n - 1 - i
for i in range(n - 1, -1, -1):
for j in range(i, n):
if s[i] == s[j] and (j - i < 2 or p[i + 1][j - 1]):
p[i][j] = True
f[i] = min(f[i], f[j + 1] + 1)
return f[0]