[TwoPointer]125. Valid Palindrom

2019-03-31  本文已影响0人  野生小熊猫

125. Valid Palindrome

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

代码:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        start=0
        end=len(s)-1
        while start<end:
            while start<end and (not s[start].isalpha()) and (not s[start].isdigit()):
                start+=1
            while start<end and (not s[end].isalpha()) and (not s[end].isdigit()):
                end-=1
            if s[start].lower()!=s[end].lower():
                return False
            start+=1
            end-=1
        return True

讨论:

  1. 一道一看就知道要用two pointer的题
  2. 到bug free用了三步:
上一篇下一篇

猜你喜欢

热点阅读