https://leetcode-cn.com/problems/implement-trie-prefix-tree/
沒看答案前隨便寫了下發現能過,但這完全是直接調輪子亂寫
class Trie {
Set<String> a = new HashSet<>();
public Trie() {
}
public void insert(String word) {
a.add(word);
}
public boolean search(String word) {
return a.contains(word);
}
public boolean startsWith(String prefix) {
for (String s:a) {
if (s.startsWith(prefix)) return true;
}
return false;
}
}
主要目的是要學習前綴樹(字典樹)
前綴樹 是一種樹形資料結構,用于高效地存盤和檢索字串資料集中的鍵,這一資料結構有相當多的應用情景,例如自動補完和拼寫檢查,
時間復雜度:初始化為 O(1),其余操作為 O(∣S∣),其中 |S| 是每次插入或查詢的字串的長度

比用哈希表快了不少

其實看了代碼之后就很好理解
class Trie {
private Trie[] children;
private boolean isEnd;
public Trie() {
children = new Trie[26];
isEnd = false;
}
public void insert(String word) {
Trie node = this;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
int index = ch - 'a';
if (node.children[index]==null) node.children[index] = new Trie();
node = node.children[index];
}
node.isEnd = true;
}
public boolean search(String word) {
Trie node = searchPrefix(word);
return node !=null && node.isEnd;
}
private Trie searchPrefix(String prefix){
Trie node = this;
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
int index = ch - 'a';
if (node.children[index]==null) return null;
node = node.children[index];
}
return node;
}
public boolean startsWith(String prefix) {
return searchPrefix(prefix) !=null;
}
}
首先以陣列形式宣告一個n個子節點(基本以26個英文字母為最大長度)
private Trie[] children;
和一個字串結尾
private boolean isEnd;
構造的時候宣告26個英文字母和為false的結尾

開始新增

把當前類作為node節點,開始遍歷傳進來的word字串,字符-‘a’獲取他的陣列位置
int index = ch - 'a';

然后記錄在 children 陣列的對應位置上
if (node.children[index]==null) node.children[index] = new Trie();
node跳到子節點繼續遍歷
node = node.children[index];
走完回圈也就到頭了,把isEnd置true

這時候就插入完成,一個完整的字典樹就建好了
多個不同字串也能進來,例如包含了三個單詞 “sea”,“sells”,“she” 的 Trie結構如圖

紅色節點的isEnd就是true
新增沒問題了,然后是search方法,他其實和startsWith方法類似,不同點在于node.isEnd的判斷

看一下共同呼叫的方法searchPrefix,和insert方法幾乎一樣

區別在于遍歷匹配節點的時候,如果不匹配,子節點肯定為null,因此回傳null;否則回傳完整的樹結構,
之后走出該方法,判斷null來區分該字串到底是不是前綴了,不等于null表示匹配成功,等于null gg
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/403908.html
標籤:其他
上一篇:如何自學成為前端程式員?學習路線是什么?前端程式員到底干什么?學完C語言然后呢?到底是選前端還是后端?
下一篇:我的Python入門之路
