题目描述:

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。

示例:

示例 1:

输入: “A man, a plan, a canal: Panama”

输出: true

示例 2:

输入: “race a car”

输出: false

解答代码:

  1. class Solution:
  2. def isPalindrome(self, s: str) -> bool:
  3. string = s.lower().replace('\n','').replace('\t','').replace('\r','').replace(' ','')
  4. if string == None:
  5. return False
  6. startLocal = 0
  7. stopLocal = len(string) - 1
  8. while startLocal < stopLocal:
  9. if string[startLocal].isdigit() or string[startLocal].isalpha():
  10. if string[stopLocal].isdigit() or string[stopLocal].isalpha():
  11. if string[stopLocal] == string[startLocal]:
  12. startLocal += 1
  13. stopLocal -= 1
  14. else:
  15. return False
  16. else:
  17. stopLocal -= 1
  18. else:
  19. startLocal += 1
  20. return True

解答思路:

难点在于整理字符串,需要注意清空特殊符号以及空格。并且在字符串读取的过程中要注意跳过标点符号。
重点是lower() replace isdigit() isalpha()四个方法。
lower:全部字母小写
replace:替换
isdigit:判断字符串是否是数字
isalpha:判断字符串是否是字母