zoukankan      html  css  js  c++  java
  • 判断回文串——相向双指针

    415. 有效回文串

    中文
    English

    给定一个字符串,判断其是否为一个回文串。只考虑字母和数字,忽略大小写。

    样例

    样例 1:

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

    样例 2:

    输入: "race a car"
    输出: false
    解释: "raceacar"
    

    挑战

    O(n) 时间复杂度,且不占用额外空间。

    注意事项

    你是否考虑过,字符串有可能是空字符串?这是面试过程中,面试官常常会问的问题。

    在这个题目中,我们将空字符串判定为有效回文。

    class Solution:
        """
        @param s: A string
        @return: Whether the string is a valid palindrome
        """
        def isPalindrome(self, s):
            # write your code here
            l, r = 0, len(s)-1
            
            def is_valid_char(c):
                return 'a' <= c <= 'z' or 'A' <= c <= 'Z' 
                        or '0' <= c <= '9'
                        
            while l <= r:
                while l <= r and not is_valid_char(s[l]):
                    l += 1
                    
                while l <= r and not is_valid_char(s[r]):
                    r -= 1
                
                if l <= r:
                    if s[l].lower() != s[r].lower():
                        return False
                    l += 1
                    r -= 1
            
            return True
    
  • 相关阅读:
    人机猜拳
    M1分数分配
    postmortem report of period M1
    视频文档分享网站场景测试说明书
    功能规格说明书
    11.9Daily Scrum
    11.6Daily Scrum
    需求博客
    11.5Daily Scrum
    11.3Daily Scrum
  • 原文地址:https://www.cnblogs.com/bonelee/p/14264842.html
Copyright © 2011-2022 走看看