美文网首页
验证回文字符串

验证回文字符串

作者: 极客匠 | 来源:发表于2019-11-29 22:26 被阅读0次

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

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

    示例 1:

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

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

    解题思路

    1. 先过滤有效的字符串,利用正则表达式只得到字符串的字母和数字,并小写生成新字符列表
    2. 通过左指针和右指针翻转后遍历比较,如果字符都相等,则是回文字符串,反之则不是
    import re
    class Solution:
        def isPalindrome(self, s: str) -> bool:
            s_temp = ''.join(re.findall(r'[a-zA-Z0-9]',s)).lower()
            l,r = s_temp[0:len(s_temp)//2],s_temp[len(s_temp)//2:len(s_temp)]
            return l == r[::-1] or l == r[::-1][:-1]
    

    相关文章

      网友评论

          本文标题:验证回文字符串

          本文链接:https://www.haomeiwen.com/subject/mcdnwctx.html