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:
- Reverse the String: Compute the reverse of the input string.
- Compute LCS: Use a space-optimized dynamic programming approach to find the length of the LCS between the original string and its reverse.
- 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
- Reverse the String: The reverse of the input string helps in finding the LPS using LCS.
- Space-Optimized LCS: We use a 1D array
dpwheredp[j]represents the length of the LCS of the firsticharacters of the original string and the firstjcharacters of the reversed string. This reduces the space complexity from O(n²) to O(n). - 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.

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