zoukankan      html  css  js  c++  java
  • [Notes] 2020.6.19 每日一题 验证回文串

    题目

    给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
    
    说明:本题中,我们将空字符串定义为有效的回文串。
    
    示例 1:
    
    输入: "A man, a plan, a canal: Panama"
    输出: true
    示例 2:
    
    输入: "race a car"
    输出: false
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/valid-palindrome
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    

    思路

    首先利用python自带的库,快速转换大小写,利用正则替换删除不需要的字符。
    然后回文验证,采用双指针,同时从前自后比对,但凡出现不一致即为错。

    代码

    class Solution:
        def isPalindrome(self, s: str) -> bool:
            if len(s.strip()) == 0:
                return True
            import re
            sl = re.sub(r'[^a-z0-9]', '', s.lower())
            for i in range(int(len(sl)/2)):
                if sl[i] != sl[-i-1]:
                    return False
            return True
    
  • 相关阅读:
    poj 2947 Widget Factory 夜
    poj 1222 EXTENDED LIGHTS OUT 夜
    poj 3440 Coin Toss 夜
    poj 1166 The Clocks 夜
    poj 3270 Cow Sorting 夜
    poj 3071 Football 夜
    poj 2409 Let it Bead 夜
    poj 1141 Brackets Sequence 夜
    hdu 4311 Meeting point1 夜
    poj 1026 Chipher 夜
  • 原文地址:https://www.cnblogs.com/immortalBlog/p/13162645.html
Copyright © 2011-2022 走看看