#208

Implement Trie (Prefix Tree)

pupil · 565 · lc medium +29 · 69.2% accepted · 12,402 likes · top 77%

play →

Description

A prefix tree (trie, pronounced "try") enables efficient string storage and lookup, powering features like autocomplete and spell-check.

Build the Trie class:

- Trie() sets up an empty trie.

- void insert(String word) stores word in the trie.

- boolean search(String word) returns true if word was previously inserted.

- boolean startsWith(String prefix) returns true if any inserted word begins with prefix.

Example 1:

Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]

Example 2:

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

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20