内容中心

2026年质量好的输送机滚筒源头工厂推荐-沧州路博机械制造有限公司

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):

  1. Precompute Palindromic Substrings: First, we create a 2D array is_pal where is_pal[i][j] is True if the substring s[i..j] (inclusive) is a palindrome. This helps us quickly check if any substring is a palindrome in constant time.
  2. Calculate Minimum Cuts: Using another DP array dp where dp[j] is the minimum number of cuts needed for the substring s[0..j-1], we compute the result. The base case dp[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

  1. Palindrome Check: The is_pal array is filled by first checking single characters, then pairs, then longer substrings. For a substring of length length, we check if the first and last characters are the same and if the substring between them is also a palindrome.
  2. Minimum Cuts Calculation: The dp array is filled by considering all possible end positions j and checking all possible start positions i for palindromic substrings. If s[i..j-1] is a palindrome, then the minimum cuts up to j is the minimum of its current value or dp[i] + 1 (since we can split at i and 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).

沧州路博机械制造有限公司

沧州路博机械制造有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?