Python实现"验证回文串"的三种方法

给定一个字符串,在只考虑字母数字且忽略字母大小写的情况下,判断该字符串是否是一个回文串

注意:空串是回文串

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

1:首先将字符串大写字母转为小写字母,然后去掉字符串中非字母和数字的其它字符,翻转对比输出结果(时间复杂度O(n))

def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s = s.lower()
        alphanumeric = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9']
        newStr = ""
        for i in s:
            if i in alphanumeric:
                newStr += i
        return newStr==newStr[::-1]

2:str.lower()+str.isalnum()(时间复杂度O(n))

def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s = s.lower()
        newStr = ""
        for i in s:
            if i.isalnum():
                newStr += i
        return newStr==newStr[::-1]

3:引入re模块(正则表达式),re.sub()

def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s = s.lower()
        import re
        s = re.sub('[^a-z0-9]', "", s)
        return s==s[::-1]

算法题来自:https://leetcode-cn.com/problems/valid-palindrome/description/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/82500940
今日推荐