题目描述:
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例:
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
示例 2:
输入: “race a car”
输出: false
解答代码:
class Solution:def isPalindrome(self, s: str) -> bool:string = s.lower().replace('\n','').replace('\t','').replace('\r','').replace(' ','')if string == None:return FalsestartLocal = 0stopLocal = len(string) - 1while startLocal < stopLocal:if string[startLocal].isdigit() or string[startLocal].isalpha():if string[stopLocal].isdigit() or string[stopLocal].isalpha():if string[stopLocal] == string[startLocal]:startLocal += 1stopLocal -= 1else:return Falseelse:stopLocal -= 1else:startLocal += 1return True
解答思路:
难点在于整理字符串,需要注意清空特殊符号以及空格。并且在字符串读取的过程中要注意跳过标点符号。
重点是lower() replace isdigit() isalpha()四个方法。
lower:全部字母小写
replace:替换
isdigit:判断字符串是否是数字
isalpha:判断字符串是否是字母
