定义
前缀树,又称字典树、单词查找树、
T
r
i
e
Trie
Trie树(发音类似 try)。它是一棵
N
N
N 叉树。前缀树的每一个结点代表一个字符串的前缀。每一个结点会有多个子结点,
通往不同子结点的路径上有着不同的字符。子结点代表的字符串是由结点本身的原始字符串,以及通往该子结点上所有的字符组成的。
前缀树的一个重要的特性是,结点所有的后代都与该结点相关的字符串有着共同的前缀,这是前缀树名称的由来。
例如,以结点 "b" 为根的子树中的结点表示的字符串,都具有共同的前缀 "b"。反之亦然,具有公共前缀 "b" 的字符串,全部位于以 "b" 为根的子树中,并且具有不同前缀的字符串来自不同的分支。
前缀树有着广泛的应用,例如自动补全,拼写检查等等。

实现 T r i e Trie Trie 树
T r i e Trie Trie,是一棵有根树,其每个结点包含以下字段:
- 指向子结点的指针数组 c h i l d r e n children children。对于本题而言,数组长度为 26,即小写字母的数量。此时 c h i l d r e n [ 0 ] children[0] children[0] 对应小写字母 a a a, c h i l d r e n [ 1 ] children[1] children[1] 对应小写字母 b b b,…, c h i l d r e n [ 25 ] children[25] children[25] 对应小写字母 z z z。
- 布尔字段 i s E n d isEnd isEnd,表示该结点是否为字符串的结尾。
插入字符串
我们从字典树的根开始,插入字符串。对于当前字符对应的子结点,有两种情况:
- 子结点存在。沿着指针移动到子结点,继续处理下一个字符。
- 子结点不存在。创建一个新的子结点,记录在 c h i l d r e n children children 数组的对应位置上,然后沿着指针移动到子结点,继续搜索下一个字符。
重复以上步骤,直到处理字符串的最后一个字符,然后将当前结点标记为字符串的结尾。
查找前缀
我们从字典树的根开始,查找前缀。对于当前字符对应的子结点,有两种情况:
- 子结点存在。沿着指针移动到子结点,继续搜索下一个字符。
- 子结点不存在。说明字典树中不包含该前缀,返回空指针。
重复以上步骤,直到返回空指针或搜索完前缀的最后一个字符。
若搜索到了前缀的末尾,就说明字典树中存在该前缀。此外,若前缀末尾对应结点的 i s E n d isEnd isEnd 为真,则说明字典树中存在该字符串。
public 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) {
Trie node = searchPrefix(word);
return node != null && node.isEnd;
}
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;
}
public boolean startsWith(String prefix) {
return searchPrefix(prefix) != null;
}
}
8799

被折叠的 条评论
为什么被折叠?



