目录
208 208. 实现 Trie (前缀树) (middle)实现insert、search、startwith 模板题必会
一、概念
Trie树,即字典树,又称单词查找树或键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较。
Trie的核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。
如果第一次接触建议:视频:https://www.bilibili.com/video/BV1Az4y1S7c7;
前缀树的3个基本性质:
- 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
- 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
- 每个节点的所有子节点包含的字符都不相同。
前缀树的创建
好比假设有b,abc,abd,bcd,abcd,efg,hii 这6个单词,那我们创建trie树就得到
二、java 代码
2.1、插入单词
//插入一个新单词
public static void insert(TrieNode root,String str){
if(root==null||str.length()==0){
return;
}
char[] c=str.toCharArray();
for(int i=0; i<str.length(); i++){
//如果该分支不存在,创建一个新节点
if(root.nextNode[c[i]-'a']==null){
root.nextNode[c[i]-'a']=new TrieNode();
}
root=root.nextNode[c[i]-'a'];
root.prefix++;//注意,应该加在后面
}
//以该节点结尾的单词数+1
root.count++;
}
2.2、查询以str开头的单词数量,查询单词str的数量
//查找该单词是否存在,如果存在返回数量,不存在返回-1
public static int search(TrieNode root, String str){
if(root==null||str.length()==0){
return -1;
}
char[] c=str.toCharArray();
// 遍历待查找字符串
for(int i=0;i<str.length();i++){
//如果该分支不存在,说明该单词不存在
if(root.nextNode[c[i]-'a']==null){
return -1;
}
//如果存在,则继续向下遍历
root=root.nextNode[c[i]-'a'];
}
//如果count==0,也说明该单词不存在
if(root.count==0){
return -1;
}
return root.count;
}
2.3、查询单词
// 查询以str为前缀的单词数量
public static int searchPrefix(TrieNode root, String str){
if(root==null||str.length()==0){
return -1;
}
char[] c=str.toCharArray();
// 遍历待查找字符串
for(int i=0;i<str.length();i++){
// 如果该分支不存在,表名该单词不存在
if(root.nextNode[c[i]-'a']==null){
return -1;
}
// 如果存在,则继续向下遍历
root=root.nextNode[c[i]-'a'];
}
return root.prefix;
}