【字符串-简单】剑指 Offer II 018. 有效的回文

643 篇文章 5 订阅

题目
代码
执行用时:60 ms, 在所有 Python3 提交中击败了26.62% 的用户
内存消耗:15.3 MB, 在所有 Python3 提交中击败了50.47% 的用户
通过测试用例:480 / 480

class Solution:
    def isPalindrome(self, s: str) -> bool:
        ans=""
        for item in s:
            num=ord(item)
            if (num>=48 and num<=57) or (num>=97 and num<=122) or (num>=65 and num<=90):
                ans+=item
        ans=ans.lower()
        return ans==ans[::-1]

【方法2】
执行用时:60 ms, 在所有 Python3 提交中击败了26.62% 的用户
内存消耗:15.3 MB, 在所有 Python3 提交中击败了50.47% 的用户
通过测试用例:480 / 480

class Solution:
    def isPalindrome(self, s: str) -> bool:
        ans=""
        for item in s:
            num=ord(item)
            if (num>=48 and num<=57) or (num>=97 and num<=122):
                ans+=item
            elif (num>=65 and num<=90):
                ans+=chr(num+32)
        return ans==ans[::-1]

【方法3】双指针
执行用时:64 ms, 在所有 Python3 提交中击败了18.63% 的用户
内存消耗:15.1 MB, 在所有 Python3 提交中击败了92.96% 的用户
通过测试用例:480 / 480

class Solution:
    def isPalindrome(self, s: str) -> bool:
        ans=True
        left,right=0,len(s)-1
        while left<right:
            while left<right and not ((s[left]>='a' and s[left]<='z') or (s[left]>='A' and s[left]<='Z') or (s[left]>='0' and s[left]<='9')):left+=1
            while left<right and not ((s[right]>='a' and s[right]<='z') or (s[right]>='A' and s[right]<='Z') or (s[right]>='0' and s[right]<='9')):right-=1
            if s[left].lower()==s[right].lower():
                left+=1
                right-=1
            else:
                return False
        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值