simple python solution (beat 99%, without node)


  • 0
    E

    It is stated in description that you may assume that all inputs are consist of lowercase letters a-z. So instead of creating a trie node, we use key = 1 to determine whether this is a word. If the word may contain the specific key, we can use others, like key 'isword'. I am not sure about any cons, all comments are welcome.

    class Trie(object):
    
        def __init__(self):
            self.d = {}
          
        def insert(self, word):
            d = self.d
            for i in word:
                if i in d:
                    d = d[i]
                else:
                    d[i] = {}
                    d = d[i]
            d[1] =  True
            
        def search(self, word):
            d = self.d
            for i in word:
                if i in d:
                    d = d[i]
                else:
                    return False
            return (1 in d)
            
     def startsWith(self, prefix):
            d = self.d
            for i in prefix:
                if i in d:
                    d = d[i]
                else:
                    return False
            return True
    

Log in to reply
 

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