Valid Palindrome
accepted answer
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# process string
s = s.lower()
s= str(s)
s = ''.join(filter(str.isalnum, s))
print()
# check
new_s = ""
for i in range(len(s)-1, -1, -1):
new_s += s[i]
if new_s == s:
return True
else:
return False
another solution with better run time:
class Solution(object):
def alnum(self, c):
return (ord('A') <= ord(c) <= ord('Z') or ord('a') <= ord(c) <= ord('z') or ord('0') <= ord(c) <= ord('9'))
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l, r = 0, len(s) - 1
while l < r:
while l < r and not self.alnum(s[l]):
l += 1
while r > l and not self.alnum(s[r]):
r -= 1
if s[l].lower() != s[r].lower():
return False
l, r = l + 1, r - 1
return True