Implement Trie (Prefix Tree) - LeetCode
Implement Trie (Prefix Tree) - LeetCode
1▾ class Trie:
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and 2
retrieve keys in a dataset of strings. There are various applications of this data structure, such as 3 def __init__(self):
4
autocomplete and spellchecker. 5
6 def insert(self, word: str)
Implement the Trie class: -> None:
7
Trie() Initializes the trie object. 8
void insert(String word) Inserts the string word into the trie. 9 def search(self, word: str)
boolean search(String word) Returns true if the string word is in the trie (i.e., was -> bool:
10
inserted before), and false otherwise. 11
boolean startsWith(String prefix) Returns true if there is a previously inserted string 12 def startsWith(self,
word that has the prefix prefix , and false otherwise. prefix: str) -> bool:
13
14
15
Example 1: 16 # Your Trie object will be
instantiated and called as
such:
Input 17 # obj = Trie()
["Trie", "insert", "search", "search", "startsWith", "insert", "search"] 18 # obj.insert(word)
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] 19 # param_2 = obj.search(word)
20 # param_3 =
Output
obj.startsWith(prefix)
[null, null, true, false, true, null, true]
Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // return True
trie.search("app"); // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app"); // return True
Constraints:
Companies
Related Topics
Similar Questions
Console Contribute