题目:
验证回文串:给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 说明:本题中,我们将空字符串定义为有效的回文串。
思路:
典型双指针的思路,比较简单,在网上找了函数isalnum()用来判断是否是字母,非常好用。
程序:
class Solution:
def isPalindrome(self, s: str) -> bool:
if not s:
return True
length = len(s)
index1 = 0
index2 = length - 1
while index1 < index2:
if not s[index1].isalnum():
index1 += 1
elif not s[index2].isalnum():
index2 -= 1
else:
if s[index1].upper() != s[index2].upper():
return False
else:
index1 += 1
index2 -= 1
return True