Given a string s, return true if it is a palindrome, otherwise return false.
A palindrome is a string that reads the same forward and backward. It is also case-insensitive and ignores all non-alphanumeric characters.
Example 1:
Input: s = "Was it a car or a cat I saw?"
Output: true Explanation: After considering only alphanumerical characters we have "wasitacaroracatisaw", which is a palindrome.
Example 2:
Input: s = "tab a cat"
Output: false Explanation: "tabacat" is not a palindrome.
In [19]:
class Solution:
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
s = s.lower()
while l < r:
# Skip non-alphanumeric characters on the left
while l < r and not s[l].isalnum():
l += 1
# Skip non-alphanumeric characters on the right
while l < r and not s[r].isalnum():
r -= 1
# Compare characters
if s[l] != s[r]:
return False
# Move pointers
l += 1
r -= 1
return True
In [20]:
print(isPalindrome("Was it a car or a cat I saw?"))
True
In [ ]: