介绍
前缀树又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
代码
/**
* 前缀树
*/
public class trie {
public static class Node {
public int pass; //通过该节点的单词数
public int end; //以该位置为结束点
public HashMap<Integer, Node> nexts;
public Node() {
pass = 0;
end = 0;
nexts = new HashMap<>();
}
}
public static class Trie2 {
private Node root;
public Trie2() {
root = new Node();
}
public void insert(String word) {
if (null == word) {
return;
}
char[] chars = word.toCharArray();
int index;
Node node = root;
for (int i = 0; i < chars.length; i++) {
index = chars[i];
if (!node.nexts.containsKey(index)) {
node.nexts.put(index, new Node());
}
// 向下前进一步
node = node.nexts.get(index);
node.pass++;
}
node.end++;
}
public void delete(String word) {
if (null == word) {
return;
}
if (search(word) != 0) {
char[] chars = word.toCharArray();
int index;
Node node = root;
for (int i = 0; i < chars.length; i++) {
index = chars[i];
if (--node.nexts.get(index).pass == 0){
node.nexts.remove(index);
}
node = node.nexts.get(index);
}
// 去除标识
node.end--;
}
}
// word这个单词之前加入过几次
public int search(String word) {
if (null == word) {
return 0;
}
char[] chars = word.toCharArray();
int index;
Node node = root;
for (int i = 0; i < chars.length; i++) {
index = chars[i];
if (!node.nexts.containsKey(index)){
return 0;
}
node = node.nexts.get(index);
}
return node.end;
}
// 所有加入的字符串中,有几个是以pre这个字符串作为前缀的
public int prefixNumber(String pre) {
if (null == pre) {
return 0;
}
char[] chars = pre.toCharArray();
int index;
Node node = root;
for (int i = 0; i < chars.length; i++) {
index = chars[i];
if (!node.nexts.containsKey(index)){
return 0;
}
node = node.nexts.get(index);
}
return node.pass;
}
}
}