208. Implement Trie (Prefix Tree)

2021. 11. 17. 18:27Leetcode

Description:

A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

  • Trie() Initializes the trie object.
  • void insert(String word) Inserts the string word into the trie.
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

 

 

class TrieNode:
    def __init__(self,char):
        self.char=char
        self.children={}
        self.isWord=False


class Trie:

    def __init__(self):
        self.root=TrieNode("")

    def insert(self, word: str) -> None:
        cur=self.root
        
        for c in word:
            if c in cur.children:
                cur=cur.children[c]
            else:
                cur.children[c]=TrieNode(c)
                cur=cur.children[c]
        cur.isWord=True
                

    def search(self, word: str) -> bool:
        cur=self.root
        
        for c in word:
            if c in cur.children:
                cur=cur.children[c]
            else:
                return False
        return cur.isWord

    def startsWith(self, prefix: str) -> bool:
        cur=self.root
        
        for c in prefix:
            if c in cur.children:
                cur=cur.children[c]
            else:
                return False
        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)