何为前缀树
在计算机科学中,trie,又称前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。
trie中的键通常是字符串,但也可以是其它的结构。
举例:
当有四个字符串时:“abc”,”bce”,”abd”,”bef”.下图中:边上的是字符,树内的数字是以当前字符结尾的字符串有多少个。比如,加入”bef”后,f后面的数字就由0–>1,再加入”be”后,‘e’处的数值就由0变成了1;求:有多少个字符串以“be”做为前缀?直接找到“be”处的’e’的数字即可。
思路
每个结点有三个属性值
- 记录有多少个字符经过这个节点
- 记录有多少个字符串以当前节点结束
- 每个节点的路径
功能
- 插入
- 将字符串转换为char数组,挨个插入
- 查找
- 怎么插入,怎么查找。返回以当前节点结束的数量
- 删除
- 首先判断是否存在(进行查找)
- 在删除到某个节点的时候,经过这个节点数量为0的时候。后面可以不考虑,直接断开
- 前缀数量
- 和查找类似,返回经过这个节点的数量
实现
public class Code_01_TrieTree {
public static class TrieNode {
public int path; // 有多少个字符到达过这个节点
public int end; // 有多少个字符串以这个字符结尾的
public TrieNode[] nexts; // 路,每个节点有多少条路
public TrieNode() {
path = 0;
end = 0;
nexts = new TrieNode[26]; // 每个结点有26条路,对应26个字母
}
}
public static class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
if (word == null) {
return;
}
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (node.nexts[index] == null) {
node.nexts[index] = new TrieNode();
}
node = node.nexts[index];
node.path++;
}
node.end++;
}
public void delete(String word) {
if (search(word) != 0) {
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
// 如果经过当前节点数量减至为0,后面不考虑,直接nexts指向null.剩余部分交给JVM回收
if (--node.nexts[index].path == 0) {
node.nexts[index] = null;
return;
}
node = node.nexts[index];
}
node.end--;
}
}
public int search(String word) {
if (word == null) {
return 0;
}
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (node.nexts[index] == null) {
return 0;
}
node = node.nexts[index];
}
return node.end;
}
public int prefixNumber(String pre) {
if (pre == null) {
return 0;
}
char[] chs = pre.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (node.nexts[index] == null) {
return 0;
}
node = node.nexts[index];
}
return node.path;
}
}
public static void main(String[] args) {
Trie trie = new Trie();
System.out.println(trie.search("zuo")); // 0
trie.insert("zuo");
System.out.println(trie.search("zuo")); // 1
trie.delete("zuo");
System.out.println(trie.search("zuo")); // 0
trie.insert("zuo");
trie.insert("zuo");
trie.delete("zuo");
System.out.println(trie.search("zuo")); // 1
trie.delete("zuo");
System.out.println(trie.search("zuo")); // 0
trie.insert("zuoa");
trie.insert("zuoac");
trie.insert("zuoab");
trie.insert("zuoad");
trie.delete("zuoa");
System.out.println(trie.search("zuoa")); // 0
System.out.println(trie.prefixNumber("zuo")); // 3
}
}