内容中心

2026年比较好的墙板剔凿综合评价公司-泰安振明建筑工程有限公司

To solve this problem, we need to determine the minimum number of deletions required to convert a given string into a palindrome. The key insight here is that the minimal deletions are equivalent to the length of the string minus the length of its longest palindromic subsequence (LPS).

Approach

The longest palindromic subsequence (LPS) of a string can be found using the Longest Common Subsequence (LCS) algorithm between the string and its reverse. This is because a palindrome reads the same forwards and backwards, so the LCS of the string and its reverse gives the longest subsequence that is a palindrome.

Steps:

  1. Reverse the String: Compute the reverse of the input string.
  2. Compute LCS: Use a space-optimized dynamic programming approach to find the length of the LCS between the original string and its reverse.
  3. Calculate Result: Subtract the length of the LCS from the length of the original string to get the minimal deletions needed.

Solution Code

def min_deletions_to_palindrome(s):
    n = len(s)
    rev = s[::-1]
    dp = [0] * (n + 1)

    for c in s:
        prev = 0  # Holds the value of dp[i-1][j-1]
        for j in range(1, n + 1):
            temp = dp[j]
            if c == rev[j-1]:
                dp[j] = prev + 1
            else:
                dp[j] = max(dp[j], dp[j-1])
            prev = temp

    return n - dp[n]

# Read input and output the result
s = input().strip()
print(min_deletions_to_palindrome(s))

Explanation

  1. Reverse the String: The reverse of the input string helps in finding the LPS using LCS.
  2. Space-Optimized LCS: We use a 1D array dp where dp[j] represents the length of the LCS of the first i characters of the original string and the first j characters of the reversed string. This reduces the space complexity from O(n²) to O(n).
  3. Result Calculation: The minimal deletions are the number of characters not part of the LPS, which is the length of the string minus the LPS length.

This approach efficiently computes the desired result with a time complexity of O(n²) and space complexity of O(n), making it suitable for most practical input sizes.

泰安振明建筑工程有限公司



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

在线客服

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