您的位置:首页 > 其它

125验证回文串

2020-07-05 07:39 495 查看

钉钉、微博极速扩容黑科技,点击观看阿里云弹性计算年度发布会!>>>

# 利用双指针,一次遍历,求出结果
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"))
































内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  panama def canal