leet125. Valid Palindrome

题目:

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.

分析:

  1. 要求判断字符串中字母和数字构成回文,首先去除干扰字符,对于种类众多,数量可能众多,规律较为复杂的干扰字符考虑使用正则替换的方式,将满足r'[^1-9a-zA-Z]+'的干扰字符替换为空字符。
  2. 对以上获得的字符串进行回文判断,将前一半字符串与后一半字符串逆向比较,如果均相同,则构成回文。
  3. 字符对比过程中,为减少大小写变换,只对确实需要的字符进行大小写变换,利用了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

思考:

  1. 本代码在leetcode中优于90%的case
  2. 本代码可以处理空字符串,以及全部由干扰字符组成的字符串
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yzpwslc

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值