• Leetcode 125.验证回文字符串(Python3)


    题目:

    给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

    说明:本题中,我们将空字符串定义为有效的回文串。

    示例 1:

    输入: "A man, a plan, a canal: Panama"
    输出: true
    

    示例 2:

    输入: "race a car"
    输出: false

    解答:


    思路:字符串去掉标点和空格后反转,反转前与反转后相同。

    方法一:

    class Solution:
        def isPalindrome(self, s):
            """
            :type s: str
            :rtype: bool
            """
            import string
            from copy import deepcopy
            enstr = string.ascii_lowercase + string.digits
            a = [i for i in s.lower() if i in enstr]
            b = deepcopy(a)
            a.reverse()
            return a == b

    方法二:使用string的内置函数isdigit()和isalpha()。

    class Solution:
        def isPalindrome(self, s):
            """
            :type s: str
            :rtype: bool
            """
            res=[]
            for x in s:
                if x.isdigit():
                    res.append(x)
                elif x.isalpha():
                    res.append(x.lower())
            return res==res[::-1]
    

    方法三:使用string的内置函数isalnum()。

    class Solution:
        def isPalindrome(self, s):
            """
            :type s: str
            :rtype: bool
            """
            s = ''.join(filter(str.isalnum,s)).lower()
            return s==s[::-1]
    

    方法四:使用正则匹配。

    class Solution:
        def isPalindrome(self, s):
            """
            :type s: str
            :rtype: bool
            """
            import re
            s = ''.join(re.findall(r"[0-9a-zA-Z]", s)).lower()
            return s == s[::-1]

    方法五:使用正则匹配。 

    import re
    class Solution:
        def isPalindrome(self, s):
            """
            :type s: str
            :rtype: bool
            """
            s = re.sub("[^A-Za-z0-9]+", "", s).lower()
            return s == s[::-1]
    

      

  • 相关阅读:
    [Unity]关于Physic Material,物理碰撞
    [Unity]当多个立方体堆叠,堆叠处出现缝隙的处理方法
    反射基础
    数据库三种事务
    一、手写ORM实现数据库查询
    UDP协议
    Wireshark抓包理解APR协议
    DBeaver用户界面窗口失效 查询窗口不显示
    二、IP、路由协议
    解决图片存入时 A generic error occurred in GDI+ 报错
  • 原文地址:https://www.cnblogs.com/tianrunzhi/p/10382068.html
Copyright © 2020-2023  润新知