leetcode筆記: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.

二. 題目分析

題目大意很簡單,就是實現字典樹,其中包括插入、查找和前綴查找三個方法。可以假設所有的輸入只包含小寫字母a-z。

本題考查字典樹數據結構的基礎知識。需要先定義TrieNode數據結構,TrieNode爲字典樹的節點,包含屬性val、children和isWord。

其中val表示當前節點所存儲的字符;children存儲了當前節點的所有子節點的指針;isWord爲布爾值,表示當前節點是否存儲了一個單詞。

Trie樹的基本性質有以下幾點:

  1. 根節點不包括字符,除根節點外,每個節點存儲一個字符;
  2. 從根節點出發,經過一系列子節點,路徑上經過的字符連接起來即爲對應的字符串。

程序設計時,一個節點的子節點最多有26個,對應26個小寫字母,因此簡單用一個數組表示。

同時,在leetcode提供的函數基礎上,增加了析構函數,因此涉及到new/delete操作。

三. 示例代碼

class TrieNode {
public:
    // Initialize your data structure here.
    char val;
    bool isWord;
    TrieNode* children[26];
    // root node
    TrieNode(): val(0), isWord(false) {
        memset(children, 0x0, sizeof(TrieNode*) * 26);
    }
    // child node
    TrieNode(char c): val(c), isWord(false) {
        memset(children, 0x0, sizeof(TrieNode*) * 26);
    }
};

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

    // Inserts a word into the trie.
    void insert(string word) {
        int n = word.length();
        if (n == 0) return;
        TrieNode* p = root;
        for (int i = 0; i < n; ++i)
        {
            char c = word[i];
            if (p->children[c - 'a'] == 0)
                p->children[c - 'a'] = new TrieNode(c);

            p = p->children[c - 'a'];
        }
        p->isWord = true;
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        int n = word.length();
        if (n == 0) return true;
        TrieNode *p = root;
        for (int i = 0; i < n; ++i)
        {
            char c = word[i];
            p = p->children[c - 'a'];
            if (p == NULL) return false;
        }
        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;
        int n = prefix.length();
        if (n == 0) return true;
        for (int i = 0; i < n; ++i)
        {
            char c = prefix[i];
            p = p->children[c - 'a'];
            if (p == NULL) return false;
        }
        return true;
    }

    // Destructor
    ~Trie() {
        freeTrieNode(root);
    }

    void freeTrieNode(TrieNode *p){  
        if (p == NULL)  
            return;  
        for (int i = 0; i < 26; ++i)  
        {  
            TrieNode *pChild = p->children[i];  
            if (pChild != NULL)  
            {  
                freeTrieNode(pChild);  
            }  
        }  
        delete p;  
    }

private:
    TrieNode* root;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");

四. 小結

鞏固字典樹數據結構。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章