125. Valid Palindrome
Given a string s, return true if it is a palindrome, considering only alphanumeric characters and ignoring case.
def is_palindrome(s):
l, r = 0, len(s) - 1
while l < r:
while l < r and not s[l].isalnum():
l += 1
while l < r and not s[r].isalnum():
r -= 1
if s[l].lower() != s[r].lower():
return False
l += 1
r -= 1
return True
One pointer starts at each end and they march toward the middle, skipping non-alphanumeric characters along the way. Any mismatch short-circuits immediately -- no need to build a cleaned-up copy of the string first.