题目描述:
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
思路:
使用双指针,现将所有字母转为小写,然后再对比。代码:
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
left,right = 0, len(s)-1
while left <right:
while left <right and not s[left].isalnum():
left += 1
while left <right and not s[right].isalnum():
right -= 1
if left<right and s[left] != s[right]:
return False
left += 1
right -= 1
return True
注意:如果写成如下:
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
left,right = 0, len(s)-1
while left <right:
while not s[left].isalnum():#没有left<right
left += 1
while not s[right].isalnum():
right -= 1
if left<right and s[left] != s[right]:
return False
left += 1
right -= 1
return True
会出现超过索引超出范围的错误:IndexError: string index out of range