何为字典树?
比如查询单词,hello那么可以通过 前缀 h 缩小范围
确定h 后再通过e 进一步缩小范围,知道最终找到hello 这个单词
字典树的示意图,来一个:
有啥用呢?
图中的四角星表示存在以该字母结尾的单词。
每个节点可以有26个子节点
只需要在插入时给每个节点计数+1 ,那么就可以很容易统计出 以当前节点结尾的前缀的单词个数
class Trie {
static class Node{
private boolean isEnd;// 标记当前节点是否为某个单词的最后一个字母
private Node[] kids;// 孩子节点数组
Node(){
isEnd=false;
kids=new Node[26];
}
}
private Node root;
/** Initialize your data structure here. */
public Trie() {
root=new Node();
}
/** Inserts a word into the trie. */
public void insert(String word) {
Node n=root;
for(int i=0;i<word.length();i++){
int c=word.charAt(i)-'a';
if(n.kids[c]==null){
n.kids[c]=new Node();
}
n=n.kids[c];
}
n.isEnd=true;// 标记为该节点为 单词末尾
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Node n=root;
for(int i=0;i<word.length();i++){
int c=word.charAt(i)-'a';
if(n.kids[c]==null){
return false;
}
n=n.kids[c];
}
return n.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Node n=root;
for(int i=0;i<prefix.length();i++){
int c=prefix.charAt(i)-'a';
if(n.kids[c]==null){
return false;
}
n=n.kids[c];
}
return true;
}
}
应用场景
输入预测,单词补全,单词检查
更详细可以移步此处
https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/shi-xian-trie-qian-zhui-shu-by-leetcode/
复杂度分析
搜索时间复杂度: o(m) m 为单词长度