My python


  • 0
    Q
    class TrieNode(object):
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.isLeaf = False
            self.children = dict()
            self.value = None
    
    class Trie(object):
    
        def __init__(self):
            self.root = TrieNode()
            self.root.value = ""
            self.root.isLeaf = True
    
        def insert(self, word):
            """
            Inserts a word into the trie.
            :type word: str
            :rtype: void
            """
            cur = self.root
            for i in range(len(word)):
                if word[i] not in cur.children:
                    newnode = TrieNode()
                    newnode.value = word[i]
                    cur.children[word[i]] = newnode
                cur = cur.children[word[i]]
            cur.isLeaf = True
    
        def search(self, word):
            """
            Returns if the word is in the trie.
            :type word: str
            :rtype: bool
            """
            cur = self.root
            for i in range(len(word)):
                if word[i] not in cur.children:
                    return False
                cur = cur.children[word[i]]
            return cur.isLeaf
    
        def startsWith(self, prefix):
            """
            Returns if there is any word in the trie
            that starts with the given prefix.
            :type prefix: str
            :rtype: bool
            """
            cur = self.root
            for i in range(len(prefix)):
                if prefix[i] not in cur.children:
                    return False
                cur = cur.children[prefix[i]]
            return True
    

Log in to reply
 

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