何爲字典樹?
比如查詢單詞,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 爲單詞長度