一個簡單的超市訂單管理系統(1)
阿新 • • 發佈:2021-10-15
字首樹
今天刷LeetCode看到了字首樹,於是我直接看(題解來自leetcode)。瞭解一下,記錄一下。
Trie,又稱字首樹或字典樹(公共字首子串樹)
其每個節點包含一下欄位:
- 指向子節點的的指標陣列children,對於208字首樹,children[0]對應小寫a···children[25]對應小寫z
- isEnd:作為判斷是否是單詞的結尾
class TrieNode { boolean isEnd;//是否是單詞的結尾 TrieNode[] children;//26個小寫字母 //構造 public TrieNode() { isEnd = true; children = new TrieNode[26]; }
//插入單詞
//插入字串 public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { int index = word.charAt(i) - 'a'; //判斷字元有沒有建立,如果沒有建立就建立 if (current.children[index] == null) { current.children[index] = new TrieNode(); //中間的字元不是完整的單詞 current.children[index].isEnd = false; } current = current.children[index]; } //最後一個字元才能構成一個完整的單詞 current.isEnd = true; }
插入字串
-
子節點存在。沿著指標移動到子節點,繼續處理下一個字元。
-
子節點不存在。建立一個新的子節點,記錄在children[] 陣列的對應位置上,然後沿著指標移動到子節點,繼續搜尋下一個字元。
private TrieNode find(String str) { TrieNode current = root; int length = str.length(); for (int i = 0; i < length; i++) { int index = str.charAt(i) - 'a'; if ((current = current.children[index]) == null) return null; } return current; } public boolean search(String word) { TrieNode current = find(word); return current != null && current.isWord; }
查詢字串
- 子節點存在。沿著指標移動到下一個節點,繼續搜尋下一個字元
- 子節點不存在,說明字典樹不包含該字首,返回空指標
重複以上步驟,直到返回空指標或搜尋完字首的最後一個字元。
若搜尋到了字首的末尾,就說明字典樹中存在該字首。此外,若字首末尾對應節點的 isEnd 為真,則說明字典樹中存在該字串。