美文网首页
208. Implement Trie (Prefix Tree

208. Implement Trie (Prefix Tree

作者: Ysgc | 来源:发表于2020-09-01 12:36 被阅读0次
    class Trie {
    private:
        class Node {
        private:
        public:
            Node () {
                next.resize(26, nullptr);
            }
            vector<shared_ptr<Node>> next;
            bool end = false;
        };
        
        shared_ptr<Node> root = make_shared<Node>();
        
    public:
        /** Initialize your data structure here. */
        Trie() {}
        
        /** Inserts a word into the trie. */
        void insert(string word) {
            shared_ptr<Node> curr_node = root;
            for (auto c : word) {
                c -= 'a';
                if (!curr_node->next[c]) {
                    curr_node->next[c] = make_shared<Node>();
                }
                curr_node = curr_node->next[c];
            }
            curr_node->end = true;   
        }
        
        /** Returns if the word is in the trie. */
        bool search(string word) {
            shared_ptr<Node> curr_node = root;
            for (auto c : word) {
                c -= 'a';
                if (!curr_node->next[c]) {
                    return false;
                }
                curr_node = curr_node->next[c];
            }
            return curr_node->end; 
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        bool startsWith(string prefix) {
            shared_ptr<Node> curr_node = root;
            for (auto c : prefix) {
                c -= 'a';
                if (!curr_node->next[c]) {
                    return false;
                }
                curr_node = curr_node->next[c];
            }
            return true;   
        }
    };
    
    /**
     * Your Trie object will be instantiated and called as such:
     * Trie* obj = new Trie();
     * obj->insert(word);
     * bool param_2 = obj->search(word);
     * bool param_3 = obj->startsWith(prefix);
     */
    

    Cautious:

    • Don't initialize vector as a member of a class outside any method
    • Resize with nullptr rather than reserve
    • "=" operator of shared_ptr can be used for reassigning.

    相关文章

      网友评论

          本文标题:208. Implement Trie (Prefix Tree

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