Given a string, we need to check whether it is possible to make this string a palindrome after removing exactly one character from this.
Input : str = “abcba”
Output : Yes
we can remove character ‘c’ to make string palindrome
Input : str = “abcbea”
Output : Yes
we can remove character ‘e’ to make string palindrome
Input : str = “abecbea”
It is not possible to make this string palindrome
just by removing one character
We can solve this problem by finding the position of mismatch. We start looping in the string by keeping two pointers at both the ends which traverse towards mid position after each iteration, this iteration will stop when we find a mismatch, as it is allowed to remove just one character we have two choices here,
At mismatch, either remove character pointed by left pointer or remove character pointed by right pointer.
We will check both the cases, remember as we have traversed equal number of steps from both sides, this mid string should also be a palindrome after removing one character, so we check two substrings, one by removing left character and one by removing right character and if one of them is palindrome then we can make complete string palindrome by removing corresponding character, and if both substrings are not palindrome then it is not possible to make complete string a palindrome under given constraint.
// C/C++ program to check whether it is possible to make
// string palindrome by removing one character
// Utility method to check if substring from low to high is
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...