Learner Level
Implement the validPalindromeAfterOneRemoval method that checks whether a text can become a palindrome after removing at most one character.
The input contains a string text. Your task is to check whether the string can become a palindrome after removing at most one character.
A palindrome reads the same from left to right and right to left. The string is also valid if it is already a palindrome without removing anything.
For example, abca can become aba by removing c, so the answer is true.
Example 1
Input
text (string) =
abcaReturns (boolean)
trueExample 2
Input
text (string) =
abcReturns (boolean)
falseExample 3
Input
text (string) =
deeeeReturns (boolean)
trueUse two pointers to compare characters from both ends of the string.
If the characters match, move both pointers inward. When a mismatch is found, there is only one removal allowed. Try skipping the left character or skipping the right character, then check whether the remaining substring is a palindrome.
If either skip produces a palindrome, return true. Otherwise, return false.
Pseudocode:
function validPalindromeAfterOneRemoval(text):
left = 0
right = length of text - 1
while left < right:
if text[left] == text[right]:
left++
right--
else:
return isPalindromeRange(text, left + 1, right) or
isPalindromeRange(text, left, right - 1)
return true
function isPalindromeRange(text, left, right):
while left < right:
if text[left] != text[right]:
return false
left++
right--
return trueReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run