|
| 1 | +# 208. Implement Trie (Prefix Tree) |
| 2 | + |
| 3 | +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. |
| 4 | + |
| 5 | +Implement the Trie class: |
| 6 | + |
| 7 | +Trie() Initializes the trie object. |
| 8 | +void insert(String word) Inserts the string word into the trie. |
| 9 | +boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise. |
| 10 | +boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise. |
| 11 | + |
| 12 | + |
| 13 | +## Example 1: |
| 14 | + |
| 15 | +**Input** |
| 16 | +["Trie", "insert", "search", "search", "startsWith", "insert", "search"] |
| 17 | +[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] |
| 18 | + |
| 19 | +**Output** |
| 20 | +[null, null, true, false, true, null, true] |
| 21 | + |
| 22 | +Explanation |
| 23 | +Trie trie = new Trie(); |
| 24 | +trie.insert("apple"); |
| 25 | +trie.search("apple"); // return True |
| 26 | +trie.search("app"); // return False |
| 27 | +trie.startsWith("app"); // return True |
| 28 | +trie.insert("app"); |
| 29 | +trie.search("app"); // return True |
| 30 | + |
| 31 | + |
| 32 | +## Constraints: |
| 33 | + |
| 34 | +1 <= word.length, prefix.length <= 2000 |
| 35 | +word and prefix consist only of lowercase English letters. |
| 36 | +At most 3 * 104 calls in total will be made to insert, search, and startsWith. |
0 commit comments