The main observation is that if the first and last characters are the same, you do not need to delete any of them; that xSTRINGx can be turned into a palindrome by deleting one letter if and only if STRING can (while STRING has at least one character in length).
You want to define a method (sorry Java syntax - I'm not a C ++ encoder):
boolean canMakePalindrome(String s, int startIndex, int endIndex, int toRemove);
which determines whether it is possible to make part of the line from startIndex to endIndex-1 in the palindrome by removing toRemove characters.
When you consider canMakePalindrome(s, i, j, r) , you can define it in terms of smaller issues like this:
- If
ji is 1, then return true; if it is 0, then return true if and only if r is 0. Here it is indicated that a 1-character string is a palindrome regardless of whether you delete the character; a line with a length of 0 lines is a palindrome, but cannot be turned into one by deleting a character (because it cannot be deleted). - If
s[i] and s[j-1] same, then this is the same answer as canMakePalindrome(s, i+1, j-1, r) . - If they differ from each other, then
s[i] or s[j-1] must be deleted. If toRemove is zero, then return false because you have no characters to delete. If toRemove is 1, return true if either canMakePalindrome(s, i+1, j, 0) or canMakePalindrome(s, i, j-1, 0) . This is because you are now checking to see if it is already a palindrome if you delete one of these two characters.
Now it can be encoded quite easily, I think.
If you want to allow the deletion of more than one character, you should use the same idea, but use dynamic programming. When deleting only one character, dynamic programming will reduce the constant coefficient, but will not reduce the asymptotic time complexity (linear along the length of the line).
source share