字典树

C++实现trid

 

class TrieNode{
public:

    TrieNode():End(false), R(26){
        links.resize(R);
    }

    void setEnd(){
        End = true;
    }

    bool isEnd(){
        return End;
    }

    bool containsKey(char key){
        return links[key - 'a'] != nullptr;
    }

    void put(char key, TrieNode* node){
        links[key - 'a'] = node;
    }

    TrieNode* get(char key){
        return links[key - 'a'];
    }

    private:
        vector<TrieNode*> links;
        bool End;
        int R;
};

class Trie {
public:
    /** Initialize your data structure here. */
    TrieNode* root;
    Trie(){
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        TrieNode* p = root;
        for(int i = 0; i < word.size(); ++i)
        {
            if(!p->containsKey(word[i]))
            {
                p->put(word[i], new TrieNode());
            }
            p = p->get(word[i]);
        }
        p->setEnd();
    }
    
    TrieNode* searchPrefix(string word)
    {
        TrieNode* p = root;
        for(int i = 0; i < word.size(); ++i)
        {
            if (p->containsKey(word[i]))
            {
                p = p->get(word[i]);
            }
            else
            {
                return nullptr;
            }
        }
        return p;
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        TrieNode* node = searchPrefix(word);
        return node != nullptr && node->isEnd();
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        TrieNode* node = searchPrefix(prefix);
        return node != nullptr;
    }
};

参考:https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/shi-xian-trie-qian-zhui-shu-by-leetcode/

posted @ 2020-02-09 14:36  强威  阅读(173)  评论(0编辑  收藏  举报