场景引入
● 给定一个数组:【goo,gi,google,goye,hi,hello】
● 要在数组中查询到前缀为go的元素
如果暴力查询是否存在某个前缀的话:
时间复杂度为: 数组长度*前缀词的长度
下面引出前缀树,来优化解决前缀匹配问题
注意:
- 前缀树的实际上属于子节点有多个的一颗树
- 在每个节点上同时需要记录当前位置的flag的值,(当指针遍历到当前flag时,若之前完全匹配,若此时flag为true则匹配到了完整的单词,若为false,说明仅仅只是词的前缀)
作用:
- 词频统计
- 前缀匹配
例题:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/797737f626547ba1150506a222f36602.png)
代码实现:
class Trie {
class TrieNode {
boolean end;
TrieNode[] children = new TrieNode[26];
}
TrieNode root;
public Trie() {
root=new TrieNode();
}
public void insert(String word) {
TrieNode temp=root;
for(char c:word.toCharArray()){
int x=c-'a';
if(temp.children[x]==null) temp.children[x]=new TrieNode();
temp=temp.children[x];
}
temp.end=true;
}
public boolean search(String word) {
TrieNode temp=root;
for(char c:word.toCharArray()){
int x=c-'a';
if(temp.children[x]==null) return false;
temp=temp.children[x];
}
return temp.end;
}
public boolean startsWith(String prefix) {
TrieNode temp=root;
for(char c:prefix.toCharArray()){
int x=c-'a';
if(temp.children[x]==null) return false;
temp=temp.children[x];
}
return true;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/