给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama" 输出: true
示例 2:
输入: "race a car" 输出: false
方法一:效率贼低,耗时一秒多,简直垃圾(博主写的!)
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower()
string = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
num = ['0','1','2','3','4','5','6','7','8','9']
temp = ''
for item in s:
if item in string or item in num:
temp += item
if temp == temp[::-1]:
return True
else:
return False
方法二:本身自己对于字符串的函数认知就不够熟练,后来赶紧恶补,发现一些很有用的函数,法二是Leetcode这道题比较好的实现方法(别人的)
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = filter(str.isalnum, str(s)).lower()
if s[::-1] == s:
return True
else:
return False