A two-pointer approach to check if a string is a valid palindrome
Original problem is here.
left) and one at the end (right).comparer.left and right pointers ever mismatch, the string is not a palindrome.isalnum() and lower().''.join() to join the filtered characters into a string.cleaned_s = ''.join(c.lower() for c in s if c.isalnum())
Note: While filtering the string upfront is very clean, an optimized solution would do this filtering on the fly during the two-pointer traversal to save $O(n)$ space.
left points to 0 (the first character).right points to len(cleaned_s) - 1 (the last character).while loop that continues as long as left < right.cleaned_s[left] and cleaned_s[right].False.left to the right by 1 and right to the left by 1 (squeezing inwards).False, it means all corresponding characters matched. We then return True.class Solution:
def isPalindrome(self, s: str) -> bool:
s = [c.lower() for c in s if c.isalnum()]
s = ''.join(s)
left = 0
right = len(s)-1
while left < right:
if s[left] == s[right]:
left += 1
right -= 1
else:
return False
return True