Given a string s
, determine if it can become a palindrome after deleting at most one character from it.
s
contain?
s
consists only of printable ASCII characters.s
?
s
will be at most (10^5).left
pointing to the beginning of the string and right
pointing to the end.left
and right
positions.left
and right
are the same, move both pointers inward.left
pointer and check if the resulting substring is a palindrome.right
pointer and check if the resulting substring is a palindrome.is_palindrome
to verify if a substring is a palindrome.def validPalindrome(s: str) -> bool:
def is_palindrome(sub: str, left: int, right: int) -> bool:
while left < right:
if sub[left] != sub[right]:
return False
left += 1
right -= 1
return True
left, right = 0, len(s) - 1
while left < right:
if s[left] == s[right]:
left += 1
right -= 1
else:
# Try skipping either the left character or the right character
return is_palindrome(s, left + 1, right) or is_palindrome(s, left, right - 1)
return True
s
. This is because, in the worst case, we might check the entire string once with two pointers and may also check one additional substring with the is_palindrome
function, but overall, we are making a linear pass.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?