125. 验证回文串
解题思路
验证回文串最直接的方法就是使用栈来进行判断,先将字符入栈,再出栈与原字符相比较。
还可以使用双指针,一个指针从头开始,一个指针从尾开始,直到两指针相遇,如果遇到不相同的则不是回文串。
代码
def isPalindrome(self, s: str) -> bool:
if s is None:
return True
s = s.lower()
# 使用栈
# stack = []
# i = 0
# while i < len(s):
# if s[i].isalpha() or s[i].isalnum():
# stack.append(s[i])
# i += 1
# return stack == stack[::-1]
# while stack and j < len(s):
# while not s[j].isalpha() and not s[j].isalnum():
# j += 1
# if stack.pop() != s[j]:
# return False
# j += 1
# return True
# 使用双指针
p1 = 0
p2 = len(s)-1
while p1 < p2:
while not (s[p1].isalpha() or s[p1].isalnum()):
p1 += 1
while not (s[p2].isalpha() or s[p2].isalnum()):
p2 -= 1
if s[p1] != s[p2]:
return False
p1 += 1
p2 -= 1
return True