算法学习

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

2020-05-04  本文已影响0人  岁月如歌2020
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: 双指针

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
上一篇下一篇

猜你喜欢

热点阅读