< Previous
Next >
Trie (we pronounce "try") or prefix tree is a tree data structure used to retrieve a key in a strings dataset. There are various applications of this very efficient data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie()
initializes the trie object.
void insert(String word)
inserts the string word
to 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.
Example 1:
Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[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:
1 <= word.length, prefix.length <= 2000
word
and prefix
consist of lowercase English letters.
- At most
3 * 104
calls will be made to insert
, search
, and startsWith
.
[Design]
[Trie]
Similar Questions
- Design Add and Search Words Data Structure (Medium)
- Design Search Autocomplete System (Hard)
- Replace Words (Medium)
- Implement Magic Dictionary (Medium)