Class Trie
java.lang.Object
g0201_0300.s0208_implement_trie_prefix_tree.Trie
208 - Implement Trie (Prefix Tree).<p>Medium</p>
<p>A <a href="https://en.wikipedia.org/wiki/Trie" target="_top"><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>
<p>Implement the Trie class:</p>
<ul>
<li><code>Trie()</code> Initializes the trie object.</li>
<li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li>
<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>
<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>
</ul>
<p><strong>Example 1:</strong></p>
<p><strong>Input</strong></p>
<pre><code> ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[ [], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
</code></pre>
<p><strong>Output:</strong> [null, null, true, false, true, null, true]</p>
<p><strong>Explanation:</strong></p>
<pre><code> 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></pre>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length, prefix.length <= 2000</code></li>
<li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li>
<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>
</ul>
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
Trie
public Trie()
-
-
Method Details
-
insert
-
search
-
search
public boolean search(String word, g0201_0300.s0208_implement_trie_prefix_tree.Trie.TrieNode root, int idx) -
startsWith
-