美文网首页算法学习
算法题--判断字符串是否合法回文

算法题--判断字符串是否合法回文

作者: 岁月如歌2020 | 来源:发表于2020-05-04 15:26 被阅读0次
    image.png

    0. 链接

    题目链接

    1. 题目

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

    Note: For the purpose of this problem, we define empty string as valid palindrome.

    Example 1:

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

    Example 2:

    Input: "race a car"
    Output: false
    

    2. 思路1: 双指针

    • 基本思路是用两个指针left和right, left从左至右, right从右至左, 逐对判断s[left]是否和s[right]表示同一个字符, 直到left和right相遇
    • 时间复杂度: ```O(N)``
    • 空间复杂度: O(1)

    3. 代码

    # coding:utf8
    
    
    class Solution:
        def isPalindrome(self, s: str) -> bool:
            left = 0
            right = len(s) - 1
            while left < right:
                while left < right and not s[left].isalnum():
                    left += 1
                while right > left and not s[right].isalnum():
                    right -= 1
                if s[left].lower() != s[right].lower():
                    return False
                else:
                    left += 1
                    right -= 1
    
            return True
    
    
    def my_test(solution, s):
        print('input: {}; output: {}'.format(s, solution.isPalindrome(s)))
    
    
    solution = Solution()
    my_test(solution, 'A man, a plan, a canal: Panama')
    my_test(solution, 'race a car')
    my_test(solution, ' ')
    my_test(solution, '0P')
    
    

    输出结果

    input: A man, a plan, a canal: Panama; output: True
    input: race a car; output: False
    input:  ; output: True
    input: 0P; output: False
    

    4. 结果

    image.png

    相关文章

      网友评论

        本文标题:算法题--判断字符串是否合法回文

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