|
| 1 | +<h2><a href="https://leetcode.com/problems/implement-trie-prefix-tree/">208. Implement Trie (Prefix Tree)</a></h2><h3>Medium</h3><hr><div><p>A <a href="https://en.wikipedia.org/wiki/Trie" target="_blank"><strong>trie</strong></a> (pronounced as "try") or <strong>prefix tree</strong> 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.</p> |
| 2 | + |
| 3 | +<p>Implement the Trie class:</p> |
| 4 | + |
| 5 | +<ul> |
| 6 | + <li><code>Trie()</code> Initializes the trie object.</li> |
| 7 | + <li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li> |
| 8 | + <li><code>boolean search(String word)</code> Returns <code>true</code> if the string <code>word</code> is in the trie (i.e., was inserted before), and <code>false</code> otherwise.</li> |
| 9 | + <li><code>boolean startsWith(String prefix)</code> Returns <code>true</code> if there is a previously inserted string <code>word</code> that has the prefix <code>prefix</code>, and <code>false</code> otherwise.</li> |
| 10 | +</ul> |
| 11 | + |
| 12 | +<p> </p> |
| 13 | +<p><strong class="example">Example 1:</strong></p> |
| 14 | + |
| 15 | +<pre style="position: relative;"><strong>Input</strong> |
| 16 | +["Trie", "insert", "search", "search", "startsWith", "insert", "search"] |
| 17 | +[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] |
| 18 | +<strong>Output</strong> |
| 19 | +[null, null, true, false, true, null, true] |
| 20 | + |
| 21 | +<strong>Explanation</strong> |
| 22 | +Trie trie = new Trie(); |
| 23 | +trie.insert("apple"); |
| 24 | +trie.search("apple"); // return True |
| 25 | +trie.search("app"); // return False |
| 26 | +trie.startsWith("app"); // return True |
| 27 | +trie.insert("app"); |
| 28 | +trie.search("app"); // return True |
| 29 | +<div class="open_grepper_editor" title="Edit & Save To Grepper"></div></pre> |
| 30 | + |
| 31 | +<p> </p> |
| 32 | +<p><strong>Constraints:</strong></p> |
| 33 | + |
| 34 | +<ul> |
| 35 | + <li><code>1 <= word.length, prefix.length <= 2000</code></li> |
| 36 | + <li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li> |
| 37 | + <li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li> |
| 38 | +</ul> |
| 39 | +</div> |
0 commit comments