Skip to content

Latest commit

 

History

History
63 lines (50 loc) · 1.4 KB

125._valid_palindrome.md

File metadata and controls

63 lines (50 loc) · 1.4 KB

###125. Valid Palindrome

题目: https://leetcode.com/problems/valid-palindrome/

难度:

Easy

根据这个palindrome原理来看,running time比较慢

class Solution(object):
    def isPalindrome(self,s):
        """
        :type s: str
        :rtype: bool
        """
        Alphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9']
        i = 0
        j = len(s) - 1
        palindrome = True
        lowerS = s.lower()
        while i < j:
            if lowerS[i] not in Alphabets:
                i += 1
                continue
            if lowerS[j] not in Alphabets:
                j -= 1
                continue
            if lowerS[i] != lowerS[j]:
                print(i,lowerS[i],j,lowerS[j])
                return False
            # s[i] == s[j]
            else:
                i += 1
                j -= 1
        return palindrome
                

当然也有取巧的办法,就是比较reversed string 和原本的是否相等. Running time 提升了一点

class Solution(object):
    def isPalindrome(self,s):
        """
        :type s: str
        :rtype: bool
        """
          
        new=[]  
  
        s=s.lower()  
  
        for i in s:  
            if '0'<=i<='9' or 'a'<=i<='z':  
                new.append(i)  
  
        return new==new[::-1]