介绍前缀树
何为前缀树? 如何生成前缀树?
是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),经常被搜索引擎系统用于文本词频统计。优点:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。字典树又称为前缀树或Trie树,是处理字符串常见的数据结构。
假设组成所有单词的字符仅是“a”~“z”,主要包含以下四个主要功能:
void insert(String word):添加word,可重复添加。
void delete(String word):删除word,如果word添加过多次,仅删除一次。
int search(String word):查询word是否在前缀树中。
int prefixNumber(String word):返回以字符串pre为前缀的单词数量。
public class TrieTree {
public static class TrieNode {
public int path;
public int end;
public TrieNode[] nexts;
public TrieNode() {
path = 0;
end = 0;
nexts = new TrieNode[26];
}
}
public static class Trie {
public TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
if (word == null) {
return;
}
char[] charArr = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < charArr.length; i++) {
index = charArr[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[] charArr = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < charArr.length; i++) {
index = charArr[i] - 'a';
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[] charArr = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < charArr.length; i++) {
index = charArr[i] - 'a';
if (node.nexts[index] == null) {
return 0;
}
node = node.nexts[index];
}
return node.end;
}
public int prefixNumber(String word) {
if (word == null) {
return 0;
}
char[] charArr = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < charArr.length; i++) {
index = charArr[i] - 'a';
if (node.nexts[index] == null) {
return 0;
}
node = node.nexts[index];
}
return node.path;
}
}
}