208. 实现 Trie (前缀树)

image.png
解法
class Trie {
private Trie[] children;
private boolean isEnd;
/** Initialize your data structure here. */
public Trie() {
// 26个字母,26叉树
children = new Trie[26];
// 判断这个节点有没有字符串结束
isEnd = false;
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie node = this;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
// 节点不存在,则在对应节点初始化
if (node.children[index] == null) {
node.children[index] = new Trie();
}
node = node.children[index];
}
node.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie node = searchTrie(word);
return node != null && node.isEnd == true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
return searchTrie(prefix) != null;
}
/**
* 统一查找,找不到就返回null
*/
private Trie searchTrie(String prefix) {
Trie node = this;
for (int i = 0; i < prefix.length(); i++) {
int index = prefix.charAt(i) - '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);
*/
本文标题:208. 实现 Trie (前缀树)
本文链接:https://www.haomeiwen.com/subject/aicailtx.html
网友评论