题目:
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.
分析:
- 要求判断字符串中字母和数字构成回文,首先去除干扰字符,对于种类众多,数量可能众多,规律较为复杂的干扰字符考虑使用正则替换的方式,将满足r'[^1-9a-zA-Z]+'的干扰字符替换为空字符。
- 对以上获得的字符串进行回文判断,将前一半字符串与后一半字符串逆向比较,如果均相同,则构成回文。
- 字符对比过程中,为减少大小写变换,只对确实需要的字符进行大小写变换,利用了or运算时若前半为真,将不验证后半部分的特性
代码:
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
newS = re.sub(r'[^0-9a-zA-Z]+','',s)
for i in range(len(newS) // 2):
if not (newS[i] == newS[-(i + 1)] or newS[i] == newS[-(i + 1)].swapcase()):
return False
return True
思考:
- 本代码在leetcode中优于90%的case
- 本代码可以处理空字符串,以及全部由干扰字符组成的字符串