valid-palindrome.py
two-pointers/valid-palindrome.py · Python · 715 B · 2026-02-17 21:08
# Check if the reversed string is equal to the original string. Or use two pointers to compare characters. # two-pointers # O(n) time, O(n) space # Reverse string def is_palindrome(s: str) -> bool: newstr = '' for c in s: if str.isalnum(c): newstr += c.lower() return newstr == newstr[::-1] # Two pointers def is_palindrome(s: str) -> bool: left = 0 right = len(s) - 1 while left < right: while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True