Why my python code get Time Limit Exceeded, I think it's O(N)


  • 0
    A
    class Solution:
    # @param {string} s
    # @return {boolean}
    def isPalindrome(self, s):
        string = ''
        for c in s:
            if c.isalpha():
                string = string + c.lower()
    
        size = len(string)
    
        if size == 0:
            return True
    
        ans = True
        mid = size /2
    
        for i in range(mid):
            if string[i] != string[-i - 1]:
                ans = False
                break
    
        return ans
    

    I don't understand. I think my code is the same as two pointer concept,
    and I test on my computer which seems right..


  • 0
    F

    I guess it is better to use lists (I don't know why but it works):

    string = []
    for c in s:
        if c.isalpha() or c.isdigit():
            string.append(c.lower())
    string = ''.join(string)
    

    Also, as you see, you should consider digit and this is how I did it:

    s = ''.join(ch for ch in s.lower() if ch != ' ' and ch not in string.punctuation)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.