To solve this problem, we need to determine if a given string is a palindrome. A palindrome reads the same forwards and backwards when ignoring non-alphanumeric characters and case differences. The solution involves using a two-pointer approach to efficiently compare characters from both ends of the string while skipping non-alphanumeric characters.
Approach
- Initialize Pointers: Start with two pointers,
left at the beginning (0) and right at the end (len(s)-1) of the string.
- Traverse Towards Center: Move the
left pointer rightwards and the right pointer leftwards until they meet:
- Skip non-alphanumeric characters by advancing the respective pointer.
- Compare the alphanumeric characters at both pointers (case-insensitive).
- If any pair of characters does not match, the string is not a palindrome.
- Termination Condition: If all corresponding alphanumeric characters match, the string is a palindrome.
Solution Code
def is_palindrome(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
Explanation
- Initialization: The
left pointer starts at the first character, and the right pointer starts at the last character.
- Skipping Non-Alphanumeric Characters: The inner loops advance the pointers past any non-alphanumeric characters (e.g., spaces, punctuation).
- Character Comparison: After positioning both pointers at alphanumeric characters, the characters are compared case-insensitively. If they don't match, the function returns
False.
- Pointer Movement: After each comparison, both pointers move towards the center (
left increases, right decreases).
- Termination: If the pointers meet or cross without any mismatches, the function returns
True, confirming the string is a palindrome.
This approach efficiently checks for palindromes by processing only relevant characters and leveraging case-insensitive comparison, ensuring optimal performance with O(n) time complexity and O(1) space complexity.