Q125 Valid Palindrome
2018-02-28 本文已影响8人
牛奶芝麻
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
解题思路:
参考题目 Q9 Palindrome Number
只包含字母或数字的回文数,因此先全部转化为小写,然后过滤掉其他非字母或非数字字符,然后反转比较。
Python实现:
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower() # 先将字符串转化为全小写
filtStr = ''
for ch in s: # 过滤掉非字母和非数字字符
if 'a' <= ch <= 'z' or '0' <= ch <= '9':
filtStr += ch
if filtStr == filtStr[::-1]:
return True
else:
return False
a = 'aBc 122-1c, b:A'
b = Solution()
print(b.isPalindrome(a)) # True