1. 程式人生 > >Leetcode 125. Valid Palindrome

Leetcode 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

Answer:

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        l=len(s)
        
        i=0
        j=l-1
        
        while i<=j:
            ic=s[i]
            jc=s[j]
            
            if not ic.isalnum():
                i+=1
                continue
            if not jc.isalnum():
                j-=1
                continue
            
            if ic.lower()!=jc.lower():
                return False
            
            i+=1
            j-=1
        return True