zoukankan      html  css  js  c++  java
  • 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]
    

      

  • 相关阅读:
    ubuntu播放器
    第一次装ubuntu 没root密码时
    web服务器记录
    socket udp编程步骤
    nfs服务器配置
    带线程函数编译条件
    linux使用一个刚编译驱动方法
    tiny6410_led驱动Makefile
    java-设计模式-外观模式
    java-实现一个简单的java Web容器
  • 原文地址:https://www.cnblogs.com/tianrunzhi/p/10382068.html
Copyright © 2011-2022 走看看