To solve this problem, we need to find the minimum number of cuts required to partition a given string into palindromic substrings.
Approach
The solution involves two main steps using dynamic programming (DP):
- Precompute Palindromic Substrings: First, we create a 2D array
is_palwhereis_pal[i][j]isTrueif the substrings[i..j](inclusive) is a palindrome. This helps us quickly check if any substring is a palindrome in constant time. - Calculate Minimum Cuts: Using another DP array
dpwheredp[j]is the minimum number of cuts needed for the substrings[0..j-1], we compute the result. The base casedp[0] = -1(since an empty string requires no cuts, and adding a palindrome to it would need one less cut than the number of parts).
Solution Code
def min_palindrome_cuts(s):
n = len(s)
if n == 0:
return 0
# Step 1: Precompute is_palindrome table
is_pal = [[False] * n for _ in range(n)]
# All single characters are palindromes
for i in range(n):
is_pal[i][i] = True
# Check for substrings of length 2
for i in range(n - 1):
if s[i] == s[i + 1]:
is_pal[i][i + 1] = True
# Check for substrings of length >=3
for length in range(3, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if s[i] == s[j] and is_pal[i + 1][j - 1]:
is_pal[i][j] = True
# Step 2: Compute minimum cuts using DP
dp = [float('inf')] * (n + 1)
dp[0] = -1 # Base case: empty string
for j in range(1, n + 1):
for i in range(j):
if is_pal[i][j - 1]:
dp[j] = min(dp[j], dp[i] + 1)
return dp[n]
# Example usage:
# input_str = "aab"
# print(min_palindrome_cuts(input_str)) # Output: 1
# To get input from user:
input_str = input().strip()
print(min_palindrome_cuts(input_str))
Explanation
- Palindrome Check: The
is_palarray is filled by first checking single characters, then pairs, then longer substrings. For a substring of lengthlength, we check if the first and last characters are the same and if the substring between them is also a palindrome. - Minimum Cuts Calculation: The
dparray is filled by considering all possible end positionsjand checking all possible start positionsifor palindromic substrings. Ifs[i..j-1]is a palindrome, then the minimum cuts up tojis the minimum of its current value ordp[i] + 1(since we can split atiand add this palindrome substring).
This approach efficiently computes the result in O(n²) time and space, which is feasible for typical input sizes. The solution handles all edge cases, including empty strings and palindromic strings (which require zero cuts).


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