Implement Trie (Prefix Tree)

題目名稱
208. Implement Trie (Prefix Tree)

描述
Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

分析
  字典樹(Trie),又稱單詞查找樹,Trie樹,是一種樹形結構,是一種哈希樹的變種。典型應用是用於統計,排序和保存大量的字符串(但不僅限於字符串),所以經常被搜索引擎系統用於文本詞頻統計。它的優點是:利用字符串的公共前綴來減少查詢時間,最大限度地減少無謂的字符串比較,查詢效率比哈希樹高。
  題目中要求我們實現三個函數:insert, search, and startsWith,並且所有的輸入都是有小寫字母組成的字符串。至於Trie樹的實現,可以用數組,也可以用指針動態分配,考慮到小寫字母共有26個,就用了數組,靜態分配空間。

結點的數據結構如下:

class TrieNode {
public:
    //存放指向下一個字符的指針數組
    vector<TrieNode*> next;
    //標記該節點是否爲一個字符串的結尾
    bool is_end;
    //constructor,初始化next的大小爲26,is_end爲false
    TrieNode():next(26),is_end(false){}
};

C++代碼

class TrieNode {
public:
    // Initialize your data structure here.
    vector<TrieNode*> next;
    bool is_end;
    TrieNode():next(26),is_end(false){}
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string word) {
        TrieNode *p = root;
        int k = 0;
        for(int i=0;i<word.size();++i) {
            k = word[i]-'a';
            if(p->next[k] == NULL){
                p->next[k] = new TrieNode();
            }
            p = p->next[k];
        }
        p->is_end = true;
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode *p = find(word);
        return p!=NULL && p->is_end;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        return find(prefix) != NULL;
    }

private:
    TrieNode* root;
    TrieNode* find(string key)
    {
        TrieNode *p = root;
        for(int i = 0; i < key.size() && p != NULL; ++ i)
            p = p -> next[key[i] - 'a'];
        return p;
    }
};

總結
  這裏只是字典樹的一個小的應用,其他的功能我會在接下來的文章中給大家分享。

發佈了129 篇原創文章 · 獲贊 45 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章