def test(fn):
= "A man, a plan, a canal: Panama"
s assert fn(s)
= "race a car"
s assert not fn(s)
= " "
s assert fn(s)
Problem Source: Leetcode
Problem Description
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s
, return true
if it is a palindrome, or false
otherwise.
tests
Solution
- Time Complexity:
O(n)
- Space Complexity:
O(1)
def isPalindrome(s: str) -> bool:
= 0, len(s)-1
lp, rp
while lp < rp:
# Ignore non-alphanumeric characters by moving pointer
# Alternative to if statements is filter(lambda x: x.isalnum(), s) prior to loop
if not s[lp].isalnum():
+= 1
lp continue
if not s[rp].isalnum():
-= 1
rp continue
# Return and exit at first failure
if s[lp].lower() != s[rp].lower():
return False
# Move to next characters
+= 1
lp -= 1
rp
# If no failures, then it's a palindrome
return True
test(isPalindrome)