美文网首页
Leetcode208: 实现Trie(前缀树)

Leetcode208: 实现Trie(前缀树)

作者: VIELAMI | 来源:发表于2020-05-25 22:49 被阅读0次
    class Trie {
    public:
        /** Initialize your data structure here. */
        Trie() {
            root_ = new TrieNode();
        }
    
        /** Inserts a word into the trie. */
        void insert(string word) {
            TrieNode* p = root_;
            for (const char c : word) {
                if (!p->children[c - 'a']) {
                    p->children[c - 'a'] = new TrieNode();
                }
                p = p->children[c - 'a'];
            }
            p->is_word = true;
        }
    
        /** Returns if the word is in the trie. */
        bool search(string word) {
            TrieNode* p = find(word);
            return (p && p->is_word);
        }
    
        /** Returns if there is any word in the trie that starts with the given prefix. */
        bool startsWith(string prefix) {
            return find(prefix) != nullptr;
        }
    
    private:
        // two basic: is_word: whether it is the end of a word
        // children : implement it with vector, storing the pointer to the child nodes
        struct TrieNode {
            bool is_word;
            vector<TrieNode*> children;
            TrieNode():is_word(false),children(26,nullptr){}
    
            ~TrieNode() {
                for (auto child : children) {
                    if (child) delete child;
                }
            }
        };
    
        // common function for realizing search & startwith
        TrieNode* find(const string& prefix) {
            TrieNode* p = root_;
            for (char c : prefix) {
                p = p->children[c - 'a'];
                if (p == nullptr) break;
            }
            return p;
        }
    
        TrieNode* root_;
    };
    

    【思路】
    前缀树的基本结构是一个最多有26个children的树

    相关文章

      网友评论

          本文标题:Leetcode208: 实现Trie(前缀树)

          本文链接:https://www.haomeiwen.com/subject/srrsahtx.html