1.什么是前缀树
-
Trie树,即字典树,又称单词查找树或键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较。
-
Trie的核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。
2.性质
- 1.根节点不包含字符,除根节点外每一个节点都只包含一个字符。
- 2.从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
- 3.每个节点的所有子节点包含的字符都不相同。
3.代码实现
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 c = word.charAt(i);
int index = c-'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;
}
//判断之前插入的字符串是否有这个前缀
public boolean startsWith(String prefix) {
return searchPrefix(prefix) != null;
}
//查找前缀
private Trie searchPrefix(String prefix){
Trie node = this;
for(int i=0;i<prefix.length();++i){
char c = prefix.charAt(i);
int index = c-'a';
if(node.children[index] == null){
return null;
}
node = node.children[index];
}
return node;
}
}