Leetcode刷题笔记22-验证回文字符串

1. 题目

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

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

2. 示例

示例 1:

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

示例 2:

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

3. 解答

python3 84ms

注意:这边需要先把非字母和数字的字符删去,然后有一些特殊的测试样例要能够通过。

扫描二维码关注公众号,回复: 1580733 查看本文章
import re
pattern = re.compile(r'[a-z0-9]')
class Solution:
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if s == '': return True
        s = s.lower()
        s0 = pattern.findall(s)
        for i in range(len(s0)//2):
            if s0[i] != s0[len(s0)-i-1]:
                return False
        return True

solution = Solution()
# s = "A man, a plan, a canal: Panama"
# s = "race a car"
# s = "0p"
# s = "a."
s = "0p"
ispalindrome = solution.isPalindrome(s)
print(ispalindrome)

猜你喜欢

转载自www.cnblogs.com/Joyce-song94/p/9176734.html