Given a string s, return true if it is a palindrome, or false otherwise. A palindrome reads the same forward and backward after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters.
- Constraints: 1 <= s.length <= 2 * 10^5,
sconsists only of printable ASCII characters. - Example:
s = "A man, a plan, a canal: Panama"
# Output: true (amanaplanacanalpanama is a palindrome)
Solution
- Two Pointers Approach: Initialize two pointers, one at the beginning (
left) and one at the end (right) of the string. - Filter & Compare: Move pointers inward, skipping non-alphanumeric characters. Compare the lowercase values of the characters at both pointers. If they mismatch, return
false. - Complexity: O(n) time complexity and O(1) auxiliary space.
class Solution:
def isPalindrome(self, s: str) -> bool:
left, right = 0, 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