Question
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
“A man, a plan, a canal: Panama” is a palindrome.
“race a car” is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
Hide Tags Two Pointers String
Analysis
Soluion
v1, Space Complexity O(n)
class Solution:
# @param {string} s
# @return {boolean}
def isPalindrome(self, s):
if s=='':
return True
s = [temp.upper() for temp in list(s)]
s = [val for val in s if ord(val) in range(65,91) or ord(val) in range(48,58)]
s_ori = s[:]
s.reverse()
return s_ori==s
v2, Space Complexity O(1)
Mistake Taken
the incorrect code is
class Solution:
# @param {string} s
# @return {boolean}
def isPalindrome(self, s):
if s=='':
return True
l,r = 0,len(s)-1
while(l<=r):
while not self.isvalid(s[l]) and l<len(s):
l += 1
while not self.isvalid(s[r]) and r<len(s):
r -= 1
if l>r or not self.issame(s[l],s[r]):
return False
return True
def isvalid(self,p):
p = p.upper()
return True if ord(p) in range(65,91) or ord(p) in range(48,58) else False
def issame(self,p,q):
p,q = p.upper(), q.upper()
return True if p==q else False
However, if the input is ″ ″, the output is False, but the expected output is True.
The solution is that in while(l<=r), moving one step(for l and r) each time. If input contains multiple ′ ′s, while(l<=r) will return nothing.
Correct code
class Solution:
# @param {string} s
# @return {boolean}
def isPalindrome(self, s):
if s=='':
return True
l,r = 0,len(s)-1
while(l<=r):
if not self.isvalid(s[l]):
l += 1
continue
if not self.isvalid(s[r]):
r -= 1
continue
if not self.issame(s[l],s[r]):
return False
l += 1
r -= 1
return True
def isvalid(self,p):
p = p.upper()
return True if ord(p) in range(65,91) or ord(p) in range(48,58) else False
def issame(self,p,q):
p,q = p.upper(), q.upper()
return True if p==q else False