208.Implement Trie (Prefix Tree)

来源:互联网 发布:淘宝网密封胶圈 编辑:程序博客网 时间:2024/06/06 04:13

Implement a trie with insertsearch, and startsWith methods.

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


class TrieNode {public:    // Initialize your data structure here.    char content;    bool isEnd;    int shared;    vector<TrieNode *> children;        TrieNode():content(' '),isEnd(false),shared(0) {            }    TrieNode(char ch):content(ch),isEnd(false),shared(0) {            }        TrieNode *subNode(char ch)    {        if(!children.empty())        {            for(auto child:children)            {                if(child->content == ch)                    return child;            }        }        return NULL;    }    ~TrieNode()    {        for(auto child:children)        {            delete child;        }    }    };class Trie {public:    Trie() {        root = new TrieNode();    }    ~Trie()    {        delete root;    }    // Inserts a word into the trie.    void insert(string word) {        if(search(word))            return;        TrieNode * cur = root;        for(auto ch:word)        {            TrieNode *child = cur->subNode(ch);            if(child)            {                cur = child;            }            else            {                TrieNode *newNode = new TrieNode(ch);                cur->children.push_back(newNode);                cur = newNode;            }            ++cur->shared;        }        cur->isEnd = true;                    }    // Returns if the word is in the trie.    bool search(string word) {        TrieNode * cur = root;        for(auto ch:word)        {            cur = cur->subNode(ch);            if(!cur)                return false;        }        return cur->isEnd == true;            }    // Returns if there is any word in the trie    // that starts with the given prefix.    bool startsWith(string prefix) {        TrieNode * cur = root;        for(auto ch:prefix)        {            cur = cur->subNode(ch);            if(!cur)                return false;        }        return true;                    }private:    TrieNode* root;};// Your Trie object will be instantiated and called as such:// Trie trie;// trie.insert("somestring");// trie.search("key");


0 0
原创粉丝点击