1. 題目要求
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
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/implement-trie-prefix-tree
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. java代碼
class Trie {
boolean isEnd;
Trie[] children;
/** Initialize your data structure here. */
//構造器,每個Trie節點包含一個子節點數組和一個結尾標志。
public Trie() {
isEnd = false;
children = new Trie[26];
}
/** Inserts a word into the trie. */
//插入操作,若字符串的前綴已在樹中,那么就在前綴之后開辟新的節點。
//若不在,就從根節點處開辟。
public void insert(String word) {
Trie node = this;
for(int i = 0; i < word.length(); i++){
int ch = word.charAt(i) - 'a';
if(node.children[ch] == null){
node.children[ch] = new Trie();
}
node = node.children[ch];
}
node.isEnd = true;
}
/** Returns if the word is in the trie. */
//查找字符串,若字符串的任意字符所對應的節點為空,那么返回false
//若字符串最后一個字符所對應的節點並非結尾,返回false
//其他情況返回true
public boolean search(String word) {
Trie node = this;
for(int i = 0; i < word.length(); i++){
int ch = word.charAt(i) - 'a';
if(node.children[ch] == null){
return false;
}
node = node.children[ch];
}
return node.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
//查找字符前綴,若前綴中的任意字符所對應的節點為空,那么返回false
//其他情況返回True
public boolean startsWith(String prefix) {
Trie node = this;
for(int i = 0; i < prefix.length(); i++){
int ch = prefix.charAt(i) - 'a';
if(node.children[ch] == null)
return false;
node = node.children[ch];
}
return true;
}
}
3. 算法效率
時間復雜度: 初始化O(1), 其他O(n)
空間復雜度:O(T*L)
(T為最長字符串的長度,L為孩子數組的長度,即字符串中字符可能的種類數。)