算法與數據結構基礎 - 字典樹(Trie)

Trie基礎git

Trie字典樹又叫前綴樹(prefix tree),用以較快速地進行單詞或前綴查詢,Trie節點結構以下:github

//208. Implement Trie (Prefix Tree)
class
TrieNode{ public: TrieNode* children[26]; //或用鏈表、map表示子節點 bool isWord; //標識該節點是否爲單詞結尾 TrieNode(){ memset(children,0,sizeof(children)); isWord=false; } };

插入單詞的方法以下:函數

    void insert(string word) {
        TrieNode* p=root;
        for(auto w:word){
            if(p->children[w-'a']==NULL) p->children[w-'a']=new TrieNode;
            p=p->children[w-'a'];
        }
        p->isWord=true;
    }

假若有單詞序列 ["a", "to", "tea", "ted", "ten", "i", "in", "inn"],則完成插入後有以下結構:spa

Trie的root節點不包含字符,以上藍色節點表示isWord標記爲true。在建好的Trie結構裏查找單詞或單詞前綴的方法以下:code

    /** Returns if the word is in the trie. */
    bool search(string word) {
        TrieNode* p=root;
        for(auto w:word){
            if(p->children[w-'a']==NULL) return false;
            p=p->children[w-'a'];
        }
        return p->isWord;
    }
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        TrieNode* p=root;
        for(auto w:prefix){
            if(p->children[w-'a']==NULL) return false;
            p=p->children[w-'a'];
        }
        return true;
    }

相關LeetCode題:blog

208. Implement Trie (Prefix Tree)  題解排序

677. Map Sum Pairs  題解leetcode

425. Word Squares  題解字符串

1032. Stream of Characters  題解get

 

Trie與Hash table比較

一樣用於快速查找,常常會拿Hash table和Trie相互比較。從以上Trie的構建和查找代碼可知,構建Trie的時間複雜度和文本長度線性相關、查找時間複雜度和單詞長度線性相關;對Trie空間複雜度來講,若是數據按前綴聚攏,那麼有利於減小Trie的存儲空間。

 

對Hash table而言,雖然查找過程是O(1),但另需考慮hash函數自己的時間消耗;另對於字符串prefix查找問題,並不能直接用Hash table解決,要麼作一些提早功夫,將各個prefix也提早存入Hash table。

相關LeetCode題:

648. Replace Words  Trie題解  HashTable題解

 

Trie的應用

Trie除了能夠用於字符串檢索、前綴匹配外,還能夠用於詞頻統計、字符串排序、搜索自動補全等場景。

相關LeetCode題:

692. Top K Frequent Words

472. Concatenated Words  題解

642. Design Search Autocomplete System  題解

相關文章
相關標籤/搜索