Trie(發音類似 "try")或者說?前綴樹?是一種樹形數據結構,用于高效地存儲和檢索字符串數據集中的鍵。這一數據結構有相當多的應用情景,例如自動補完和拼寫檢查。
請你實現 Trie 類:
Trie()
?初始化前綴樹對象。void insert(String word)
?向前綴樹中插入字符串?word
?。boolean search(String word)
?如果字符串?word
?在前綴樹中,返回?true
(即,在檢索之前已經插入);否則,返回?false
?。boolean startsWith(String prefix)
?如果之前已經插入的字符串?word
?的前綴之一為?prefix
?,返回?true
?;否則,返回?false
?。
示例:
輸入 ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] 輸出 [null, null, true, false, true, null, true]解釋 Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // 返回 True trie.search("app"); // 返回 False trie.startsWith("app"); // 返回 True trie.insert("app"); trie.search("app"); // 返回 True
提示:
1 <= word.length, prefix.length <= 2000
word
?和?prefix
?僅由小寫英文字母組成insert
、search
?和?startsWith
?調用次數?總計?不超過?3 * 104
?次
解題思路
- 用到字典樹和前綴樹的思想
- 字典樹指的是結點包含一個子結點數組,用一個標記判斷是否為一個單詞,
- 如果標記為false說明從根節點到當前結點只是一個完整單詞的前綴的一部分
- 如果標記為true說明從根節點到當前結點存在一個完整的單詞
- 用到字符減去字符'a'得到該字符的相對索引值再為該索引下的數組元素new 一個 Trie對象用于后面判斷該字符是否存在
- 若該字符轉化為索引對應的數組元素值不為空說明該字符存在
- 否則說明該字符不存在
class Trie {private Trie[] children;private boolean isEnd;public Trie(){this.children=new Trie[26];}public void insert(String word) {Trie head=this;int index=-1;for(int i=0;i<word.length();i++){index=word.charAt(i)-'a';if(head.children[index]==null){head.children[index]=new Trie();}head=head.children[index];}head.isEnd=true;}public boolean search(String word) {Trie head=this;int index=-1;for(int i=0;i<word.length();i++){index=word.charAt(i)-'a';if(head.children[index]==null)return false;head=head.children[index];}if(head.isEnd)return true;return false;}public boolean startsWith(String prefix) {Trie head=this; int index=-1;for(int i=0;i<prefix.length();i++){index=prefix.charAt(i)-'a';if(head.children[index]==null)return false;head=head.children[index];}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);*/