topic
A Trie (pronounced like "try") or prefix tree is a tree-like data structure used to efficiently store and retrieve keys from a string dataset. This data structure has quite a few applications, such as autocompletion and spell checking.
Please implement the Trie class:
Trie()
Initialize the prefix tree object.void insert(String word)
Insert a string into the prefix treeword
.boolean search(String word)
If the stringword
is in the prefix tree, return ittrue
(that is, it was inserted before retrieval); otherwise, return itfalse
.boolean startsWith(String prefix)
Returns ifword
one of the prefixes of the previously inserted string is ; otherwise, returns .prefix
true
false
Example:
enter ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] output [null, null, true, false, true, null, true] explain Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns True trie.search("app"); // returns False trie.startsWith("app"); // returns True trie.insert("app"); trie.search("app"); // returns True
hint:
1 <= word.length, prefix.length <= 2000
word
andprefix
consist only of lowercase English lettersinsert
,search
and the totalstartsWith
number of calls does not exceed3 * 10^4
answer
source code
class Trie {
private Trie[] children;
private boolean isEnd;
public Trie() {
children = new Trie[26];
isEnd = false;
}
public void insert(String word) {
Trie node = this;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
int index = ch - 'a';
if (node.children[index] == null) {
node.children[index] = new Trie();
}
node = node.children[index];
}
node.isEnd = true;
}
public boolean search(String word) {
return searchPrefix(word) != null && searchPrefix(word).isEnd;
}
public boolean startsWith(String prefix) {
return searchPrefix(prefix) != null;
}
private Trie searchPrefix(String prefix) {
Trie node = this;
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
int index = ch - 'a';
if (node.children[index] == null) {
return null;
}
node = node.children[index];
}
return node;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/
Summarize
It's a bit complicated... the first time I didn't bother to give up, and the second time I got AC.
The official solution is actually equivalent to a 26-fork number. The member variable children array represents the next letter, the 0 index corresponds to 'a', and the 25 index corresponds to 'z'; isEnd indicates whether the current letter is the end of a word.