To solve this problem, we need to determine the minimum number of insertions required to convert a given string into a palindrome. The key insight here is leveraging the relationship between the Longest Palindromic Subsequence (LPS) and the minimum insertions needed.
Approach
- Longest Palindromic Subsequence (LPS): The LPS of a string is the longest sequence of characters that reads the same forwards and backwards. The minimum number of insertions required to make the string a palindrome is the length of the string minus the length of its LPS. This is because the LPS is the largest part of the string that is already a palindrome, so the remaining characters need to be mirrored.
- Longest Common Subsequence (LCS): The LPS of a string can be found by computing the LCS between the string and its reverse. This is because the LCS of a string and its reverse gives the longest sequence that appears in both, which is a palindrome.
Solution Code
s = input().strip()
n = len(s)
rev_s = s[::-1]
dp = [0] * (n + 1)
for char in s:
for j in range(n, 0, -1):
if char == rev_s[j-1]:
dp[j] = dp[j-1] + 1
else:
dp[j] = max(dp[j], dp[j-1])
print(n - dp[n])
Explanation
- Reverse the String: First, we reverse the input string to get
rev_s. - Dynamic Programming (DP) for LCS: We use a 1D DP array to compute the LCS of the original string and its reverse. The 1D array optimizes space by reusing the previous row's values.
- DP Array Initialization: The
dparray of sizen+1(wherenis the length of the string) is initialized to zero. - DP Transition: For each character in the original string, we iterate over the reversed string from right to left. If the characters match, we increment the value from the previous position. Otherwise, we take the maximum value from the current or previous position.
- DP Array Initialization: The
- Calculate Result: The result is the length of the string minus the length of the LCS (which is the LPS length), giving the minimum insertions needed.
This approach efficiently computes the result with a time complexity of O(n²) and space complexity of O(n), making it suitable for most practical cases.
Answer: The minimum number of insertions required to make the string a palindrome is printed as the result. For example, if the input string is "abc", the output will be 2. If the input string is "racecar", the output will be 0. If the input string is "ab", the output will be 1. The code handles all these cases correctly.


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