Skip to content

Latest commit

 

History

History
75 lines (59 loc) · 1.49 KB

208.md

File metadata and controls

75 lines (59 loc) · 1.49 KB

208 Implement Trie (Prefix Tree)

Description

link


Solution

See Code


Code

O(1)

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.trie = collections.defaultdict(Trie)
        self.end = False

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        node = self
        for w in word:
            if w not in node.trie:
                node.trie[w] = Trie()
            node = node.trie[w]
        node.end = True
            
    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        node = self
        for w in word:
            if w not in node.trie:
                return False
            node = node.trie[w]
        return node.end

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        node = self
        for w in prefix:
            if w not in node.trie:
                return False
            node = node.trie[w]
        return True
        
        

# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)