class Solution:
"""
main idea: to strip space and check each char if they are alphabetic or numeric, if not, skip and save it into res (initialize with empyt string), and compare from beginning and end
time O(N) space O(N)
"""
def isPalindrome(self, s: str) -> bool:
res = ''
s = s.strip()
for c in s:
if not c.isalnum():
if not c.isdigit():
continue
else:
res += c.lower()
else:
res += c.lower()
return res[::] == res[::-1]
optimization space O(1)
class Solution:
"""
main idea: two pointers. start from two ends, to remove spaces: under big assumption of l< r ,using str.isalnum() whithin while loop to increament left ptr or decrement right ptr;
"""
def isPalindrome(self, s: str) -> bool:
# time O(N) space O(1)
l,r =0,len(s)-1
while l < r:
while l < r and not s[l].isalnum():
l += 1
while l < r and not s[r].isalnum():
r -= 1
if s[l] == s[r] or s[l].lower()==s[r].lower(): # add addition al s[l]== s[r] check to speed up
l += 1
r -= 1
else:
return False
return True