Clean relatively fast Python solution


  • 0
    P

    Feedback appreciated!
    368 ms

    class TrieNode(object):
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.letters = {}
    
    class Trie(object):
    
        def __init__(self):
            self.root = TrieNode()
    
        def insert(self, word):
            """
            Inserts a word into the trie.
            :type word: str
            :rtype: void
            """
            temp = self.root
            for i, ch in enumerate(word):
                if ch not in temp.letters:
                    temp.letters[ch] = TrieNode()
                temp = temp.letters[ch]
            temp.letters[1] = True
    
        def search(self, word):
            """
            Returns if the word is in the trie.
            :type word: str
            :rtype: bool
            """
            temp = self.root
            for ch in word:
                if ch in temp.letters:
                    temp = temp.letters[ch]
                else:
                    return False
            return 1 in temp.letters
                
        def startsWith(self, prefix):
            """
            Returns if there is any word in the trie
            that starts with the given prefix.
            :type prefix: str
            :rtype: bool
            """
            temp = self.root
            for ch in prefix:
                if ch in temp.letters:
                    temp = temp.letters[ch]
                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.