Trie樹(字典樹)的實現

Lintcode 442上實現Trie樹
http://www.lintcode.com/zh-cn/problem/implement-trie/

class TrieNode{
public:
    TrieNode()
    {
        for(int i = 0; i < 26; i++)
        {
            children[i] = nullptr;
            isEnd = false;
        }
    }
public:
    char data;
    TrieNode * children[26];
    bool isEnd;
};

class Trie {
public:
    Trie() {
        // do intialization if necessary
        root = new TrieNode();
    }

    /*
     * @param word: a word
     * @return: nothing
     */
    void insert(string &word) {
        // write your code here
        int wordLen = word.length();
        if(wordLen > 0)
        {
            TrieNode * cur = root;
            for(int index = 0; index < wordLen; index++)
            {
                int childIndex = word[index] - 'a';
                if(cur->children[childIndex] == nullptr)
                {
                    cur->children[childIndex] = new TrieNode();
                    cur->children[childIndex]->data = word[index];
                }
                cur = cur->children[childIndex];
            }
            cur->isEnd = true;
        }
    }

    /*
     * @param word: A string
     * @return: if the word is in the trie.
     */
    bool search(string &word) {
        // write your code here
        int wordLen = word.length();
        if(wordLen > 0)
        {
            TrieNode * cur = root;
            for(int index = 0; index < wordLen; index++)
            {
                int childIndex = word[index] - 'a';
                if(cur->children[childIndex] == nullptr)
                {
                    return false;
                }
                cur = cur->children[childIndex];
            }
            if(cur->isEnd)
            {
                return true;
            }
        }
        return false;
    }

    /*
     * @param prefix: A string
     * @return: if there is any word in the trie that starts with the given prefix.
     */
    bool startsWith(string &prefix) {
        // write your code here
        int wordLen = prefix.length();
        if(wordLen > 0)
        {
            TrieNode * cur = root;
            for(int index = 0; index < wordLen; index++)
            {
                int childIndex = prefix[index] - 'a';
                if(cur->children[childIndex] == nullptr)
                {
                    return false;
                }
                cur = cur->children[childIndex];
            }
            return true;
        }
        return false;
    }
private:
    TrieNode * root;
};
發佈了92 篇原創文章 · 獲贊 21 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章