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]
    

      

  • 相关阅读:
    Java POI 导出EXCEL经典实现 Java导出Excel
    Sublime Text 3 相关
    phonegap 4.2 环境搭建 及 项目创建 运行
    Js 简单分页(一)
    VC调试闪退解决办法
    查找一个数中1的个数
    居中详解
    解决ajax跨域请求 (总结)
    js实现css3的过渡,需要注意的一点(浏览器优化)
    reflow和repaint(摘录自张鑫旭的翻译)
  • 原文地址:https://www.cnblogs.com/tianrunzhi/p/10382068.html
Copyright © 2011-2022 走看看