Skip to content

Latest commit

 

History

History
59 lines (45 loc) · 1.24 KB

125. Valid Palindrome.md

File metadata and controls

59 lines (45 loc) · 1.24 KB

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

Solution

两指针指向头尾,往中间靠拢,直到两边都是字母/数字,比较,相同就continue,不同就break。

Code

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        length = len(s)
        flag = True
        if length <= 1:
            return flag
        head = 0
        tail = length-1
        s = s.lower()
        while head < tail:
            while head<length and not s[head].isalnum():
                head += 1
            while tail >=0 and not s[tail].isalnum():
                tail -= 1
            if head<length and tail>=0:
                if s[head] == s[tail]:
                    tail -= 1
                    head += 1
                    continue
                else:
                    flag = False
                    break
            
        return flag