125验证回文串

# 利用双指针,一次遍历,求出结果
class Solution:
def isPalindrome(self, s: str) -> bool:
# 定义变量,接收字符串的长度
length = len(s)
# 长度小于等于1直接返回真
if length <= 1:return True
# 定义两个指针, 分别指向字符串头和尾
index1,index2 = 0,length - 1
while index1 <= index2:
# 判断字符是否为字母或者数字
if not s[index1].isalnum():
index1 += 1
continue
if not s[index2].isalnum():
index2 -= 1
continue
# 判断两个字符是否相同
if s[index1].lower() != s[index2].lower():
return False
index1 += 1
index2 -= 1
return True

A = Solution()
print(A.isPalindrome("A man, a plan, a canal: Panama"))
print(A.isPalindrome(""))
print(A.isPalindrome("qq"))
print(A.isPalindrome("race a car"))


posted @ 2020-07-04 21:02  月为暮  阅读(174)  评论(0编辑  收藏  举报