Chapter 18: Tries
前言
The trie (pronounced as try) is a tree that specializes in storing data that can be represented as a collection, such as English words.
大綱
Example
Implementation
TrieNode
Trie
Insert
Contains
Remove
Prefix matching
Example
什麼情況會用到trie這個結構。ex. 進行字串比對

利用暴力比對法
The time complexity of words(matching:) is O(k*n), where k is the longest string in the collection, and n is the number of words you need to check
TrieNode

Trie
Insert
時間複雜度: O(K), k是collection的長度,因為要重複k次,把collection每個元素一一進行插入。
Contains
時間複雜度: O(K), k是collection的長度,因為要重複k次,把collection每個元素一一進行檢查確認。
Remove
時間複雜度: O(K), k是collection的長度,因為要重複k次,把collection每個元素一一進行刪除。
Prefix matching
這個Trie最經典有名的應用了
時間複雜度: k: 是在collection中符合prefix的長度, m: 是在目前collection中符合當前prefix的數量,原本暴力算法是n,每次都要比對原始collection的數量, 透過trie讓m會小於n
collection(startingWith:) has a time complexity of O(km), where k represents the longest collection matching the prefix and m represents the number of collections that match the prefix. Recall that arrays have a time complexity of O(kn), where n is the number of elements in the collection.
Last updated