字典树又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
jvav 实现代码如下
public class Trie {
private Node root;
public Trie() {
root = new Node();
}
//添加字符串string
void insert(String string) {
if (string == null) return;
char[] str = string.toLowerCase().toCharArray();
Node node = root;
node.p++;
int index = 0;
for (int i = 0; i < str.length; i++) {
index = str[i] - 'a';
if (node.next[index] == null) node.next[index] = new Node();
node.next[index].p++;
node = node.next[index];
}
node.e++;
}
//有几个字符串string
int search(String string) {
if (string == null) return -1;
//if (root.p == 0) return -2;
char[] str = string.toLowerCase().toCharArray();
Node node = root;
int index = 0;
for (int i = 0; i < str.length; i++) {
index = str[i] - 'a';
//if (node.next[index] == null || node.next[index].p == 0) return 0;
if (node.next[index] == null) return 0;
node = node.next[index];
}
return node.e;
}
//有几个字符串以string开头
int prefix(String string) {
if (string == null) return -1;
//if (root.p == 0) return -2;
char[] str = string.toLowerCase().toCharArray();
Node node = root;
int index = 0;
for (int i = 0; i < str.length; i++) {
index = str[i] - 'a';
//if (node.next[index] == null || node.next[index].p == 0) return 0;
if (node.next[index] == null) return 0;
node = node.next[index];
}
return node.p;
}
//删除字符串string
boolean delete(String string) {
if (search(string) < 1) return false;
char[] str = string.toLowerCase().toCharArray();
Node node = root;
int index = 0;
node.p--;
for (int i = 0; i < str.length; i++) {
index = str[i] - 'a';
if (--node.next[index].p == 0) {
node.next[index] = null;
return true;
}
node = node.next[index];
}
node.e--;
return true;
}
}
class Node {
public int p;
public int e;
public Node[] next;
public Node() {
p = 0;
e = 0;
next = new Node[26];
}
}
此数据结构可用于储存任意26个字母组成的字符串,并实现增删查,查前缀功能。
世界线回溯,从jvav到架构师