一、什麼是Trie字典樹
Trie字典樹(主要用於存儲字符串)查找速度主要和它的元素(字符串)的長度相關[O(w)]。
Trie字典樹主要用於存儲字符串,Trie 的每個 Node 保存一個字符。用鏈表來描述的話,就是一個字符串就是一個鏈表。每個Node都保存了它的所有子節點。
使用場景:通訊錄高效搜索,專爲處理字符串設計的。
比如字典中有n條數據,如果使用樹結構,查詢的時間複雜度是O(logn),如果有100萬條數據的話,logn大約是20,如果有1億條數據的話,logn大約是30(參考2的N次方計算器)
時間複雜度爲:O(w),w爲單詞的長度。
例如我們往字典樹中插入cat、dog、deef、panda四個單詞,Trie字典樹如下所示:
也就是說如果只考慮小寫的26個字母,那麼Trie字典樹的每個節點都可能有26個子節點。
二、Trie字典樹的基本操作
1、插入
本文是使用鏈表來實現Trie字典樹,字符串的每個字符作爲一個Node節點,Node主要有兩部分組成:
- 是否是單詞 (boolean isWord)
- 節點所有的子節點,用map來保存 (Map next)
例如插入一個paint單詞,如果用戶查詢pain,儘管 paint 包含了 pain,但是Trie中仍然不包含 pain 這個單詞,所以如果往Trie中插入一個單詞,需要把該單詞的最後一個字符的節點的 isWord 設置爲 true。所以爲什麼Node需要存儲 是否是單詞 這個屬性。
節點的所有子節點,通過一個Map來存儲,key是當前子節點對應的字符,value是子節點。
import java.util.TreeMap;
public class Trie {
private class Node{
public boolean isWord; // 是否是單詞 (boolean isWord)
// 節點所有的子節點,用map來保存 (Map next)
public TreeMap<Character, Node> next;
public Node(boolean isWord){
this.isWord = isWord;
next = new TreeMap<>();
}
public Node(){
this(false);
}
}
private Node root;
private int size; // 存儲單詞的個數
public Trie(){
root = new Node();
size = 0;
}
// 獲得Trie中存儲的單詞數量
public int getSize(){
return size;
}
// 向Trie中添加一個新的單詞word
public void add(String word){
Node cur = root;
for(int i = 0 ; i < word.length() ; i ++){
char c = word.charAt(i);
if(cur.next.get(c) == null) // 一個字符對應一個Node節點
cur.next.put(c, new Node());
cur = cur.next.get(c);
}
// 如果當前的node已經是一個word,則不需要添加
if(!cur.isWord){
cur.isWord = true;
size ++;
}
}
}
2、查詢
Trie查找操作遍歷帶查找的字符串的字符,如果每個節點都存在,並且待查找字符串的最後一個字符對應的Node的 isWord 屬性爲 true ,則表示該單詞存在
// 查詢單詞word是否在Trie中
public boolean contains(String word){
Node cur = root;
for(int i = 0 ; i < word.length() ; i ++){
char c = word.charAt(i);
if(cur.next.get(c) == null)
return false;
cur = cur.next.get(c);
}
return cur.isWord;
}
3、前綴查詢
前綴查詢和上面的查詢操作基本類似,就是不需要判斷 isWord 了
// 查詢是否在Trie中有單詞以prefix爲前綴
public boolean isPrefix(String prefix){
Node cur = root;
for(int i = 0 ; i < prefix.length() ; i ++){
char c = prefix.charAt(i);
if(cur.next.get(c) == null)
return false;
cur = cur.next.get(c);
}
return true;
}
4、Trie字典樹搜索和正則匹配
對應Leetcode 211題添加與搜索單詞
參考模型
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
return match(root, word, 0);
}
private boolean match(Node node, String word, int index){
if(index == word.length())
return node.isWord;
char c = word.charAt(index);
if(c != '.') {
if(node.next.get(c) == null)
return false;
return match(node.next.get(c), word, index + 1);
} else {
for(char nextChar: node.next.keySet()) {
if(match(node.next.get(nextChar), word, index + 1))
return true;
}
return false;
}
}