力扣每日一刷--验证回文串

验证回文串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
我的代码

class Solution:
    def isPalindrome(self, s: str) -> bool:
        li = []
        if s.isspace():
            return True

        for each in s:
            if each.isalnum():
                li.append(each)
            else:
                continue

        # 双指针
        low = 0
        high = len(li) - 1
        while low < high:
            if li[low].upper() == li[high].upper():
                low = low + 1
                high = high - 1
            else:
                return False
        # 循环退出时,low== high,此时,说明都相等
        return True

别人的代码:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = s.lower()
        left, right = 0, len(s) - 1
        while left < right:
            # 两个循环找到左侧和右侧为字母或者数字的位置
            while left < len(s) - 1 and not s[left].isalnum():
                left += 1
            while right > 0 and not s[right].isalnum():
                right -= 1
            if left >= right:  # 判断移动过后的left right是否满足left在左,right在右的相对位置
                break
            else:
                if s[left] != s[right]:  # 如果左右指针所指不同,则肯定不构成回文
                    return False
                else:  # 左右指针各前进一步
                    left += 1
                    right -= 1
        return True

另一思路:正则表达式
^ [a-zA-Z]是去匹配目标字符串中以中括号中的a—z或者A—Z开头的字符
[^a-zA-Z]是去匹配目标字符串中非a—z也非A—Z的字符

import re
class Solution:
    def isPalindrome(self, s: str) -> bool:
    	# re.sub(正则表达式,新内容,string)   替换
        s=re.sub('[^a-zA-Z0-9]','',s)
        s=s.lower()
        return s==s[::-1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值