125. Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama" Output: true
Example 2:
Input: "race a car" Output: false
解题思路
由于题目中字母是大小写无关的,因此可以先使用函数 lower() 将字符串中的字母全部转换成小写,再把字符串中的非数字字母字符删去,这个可以调用字符串函数 replace() 来实现,第一个参数为要替换的字符,第二个参数为一个空字符,通过比较反转后的字符串与原字符串相比较来得到结果,反转字符串可以使用步长-1实现,具体运算符为 [::-1]
代码
class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ s = s.lower() i=0 while i<len(s): if(s[i].isalnum()==False): x = s[i] s = s.replace(x,'') else: i+=1 return s[::-1]==s