Trie树(字典树)的实现

来源:互联网 发布:php上传文件源码 编辑:程序博客网 时间:2024/05/16 14:04

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;};
原创粉丝点击