import sys
class Solution:
def minCut(self, s: str) -> int:
'''
state: dp[i]表示s[:i+1]的最少分割次数
basecase: [sys.maxsize] * n 用于min函数的比较
transfer: 考虑s[:i+1]的最后一个回文子串,假设其为s[j+1:i+1],
则dp[i] = min(dp[i], dp[j]+1)
注意的是,如果s[:i+1]本身就是一个回文串,则dp[i]=0
result: dp[-1]
'''
n = len(s)
# 首先判断s的每一个字串是否为回文串,并储存结果
# 以使得下一步涉及的判断回文串操作为O(1)
check = [[True] * n for _ in range(n)]
for i in range(n-1, -1, -1):
for j in range(i+1, n):
check[i][j] = (check[i+1][j-1] and s[i] == s[j])
# 得到最少分割次数的主操作
dp = [sys.maxsize] * n
for i in range(n):
if check[0][i]:
dp[i] = 0
else:
for j in range(i):
if check[j+1][i]:
dp[i] = min(dp[i], dp[j]+1)
return dp[-1]
11-04
8980
03-07
680
06-13
502