To solve this problem, we need to find the minimum number of cuts required to partition a given string such that every substring of the partition is a palindrome. This problem can be efficiently solved using dynamic programming (DP) with precomputation of palindromic substrings.
Approach
-
Precompute Palindromic Substrings: First, we create a 2D array
is_palwhereis_pal[i][j]isTrueif the substrings[i..j]is a palindrome. This is done using DP:- A substring
s[i..j]is a palindrome ifs[i] == s[j]and either the substring length is ≤ 2 (trivially a palindrome) or the substrings[i+1..j-1]is a palindrome.
- A substring
-
Compute Minimum Cuts: Next, we use another DP array
dpwheredp[i]is the minimum number of cuts needed for the substrings[0..i]:- If
s[0..i]is a palindrome,dp[i]is 0 (no cuts needed). - Otherwise, for each
jfrom 1 toi, ifs[j..i]is a palindrome, thendp[i]is the minimum of its current value anddp[j-1] + 1(cut afterj-1to gets[j..i]as a palindrome).
- If
Solution Code
def minCut(s):
n = len(s)
if n == 0:
return 0
# Precompute is_pal[i][j] = True if s[i..j] is a palindrome
is_pal = [[False] * n for _ in range(n)]
for i in range(n-1, -1, -1):
for j in range(i, n):
if s[i] == s[j]:
if j - i <= 1:
is_pal[i][j] = True
else:
is_pal[i][j] = is_pal[i+1][j-1]
else:
is_pal[i][j] = False
# Compute dp[i] = min cuts for s[0..i]
dp = [float('inf')] * n
dp[0] = 0 # single character needs no cuts
for i in range(1, n):
if is_pal[0][i]:
dp[i] = 0
else:
for j in range(1, i+1):
if is_pal[j][i]:
dp[i] = min(dp[i], dp[j-1] + 1)
return dp[-1]
Explanation
- Precompute Palindromic Substrings: The
is_palarray is filled from the end of the string to the start. This allows us to use previously computed values for shorter substrings to determine longer ones. - Minimum Cuts Calculation: The
dparray is built by checking all possible palindromic substrings ending at each positioni. For each valid palindrome starting atj, we update the minimum cuts needed fors[0..i]using the cuts needed fors[0..j-1].
This approach efficiently computes the solution with a time complexity of O(n²) (due to the two nested loops for is_pal and dp), which is optimal for this problem. The space complexity is O(n²) for the is_pal array, which is manageable for most practical string lengths.
Example: For the string "aab", the minimum cuts are 1 (partition into ["aa", "b"]). The code correctly returns this result. For "abc", the minimum cuts are 2 (partition into ["a", "b", "c"]).
This solution handles all edge cases, including empty strings, single characters, and fully palindromic strings. It provides an optimal way to find the minimum number of cuts for palindrome partitioning.


作者声明:本文包含人工智能生成内容。