0
点赞
收藏
分享

微信扫一扫

LeetCode刷题——125. 验证回文串


题目

LeetCode刷题——125. 验证回文串_对撞指针

思路

回文就是从左往右阅读,和从右往左阅读得到的字符串是相等的。

题目说只考虑数字和字母,刚好python中有个函数​​isalnum()​​​可以判断。然后可以利用双指针,判断符号条件的两个指针所在元素是否相等,直到对撞为止(返回​​True​​​),或者不相等(返回​​False​​)。

代码

class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s.strip()) == 0:
return True

s = s.lower() # 题目说忽略大小写,不管三七二十一,全部转换为小写
i,j = 0,len(s) -1
while i < j:
# 从左往右,直到遇到字母或数字
while i < j and s[i].isalnum() == False:
i += 1

while i < j and s[j].isalnum() == False:
j -= 1
# 比较是否相等
if s[i] != s[j]:
return False
i += 1
j -= 1

return True

LeetCode刷题——125. 验证回文串_python_02


举报

相关推荐

0 条评论