Leetcode——208. Implement Trie (Prefix Tree) C++语言实现Tire

来源:互联网 发布:进销存哪种软件好 编辑:程序博客网 时间:2024/06/05 19:14
//slower than recursive versionclass Trie {private:    static constexpr int R = 26;    struct Node {        bool is_word = false;        Node *next = nullptr;    };public:    //~Trie(); How to write efficient dectructor?    void insert(string word) {        if (word.empty()) return;        Node *x = &root;        int p = 0;        while (p < word.size()) {            if (!x->next) x->next = new Node[R];            x = &x->next[word[p++] - 'a'];        }        x->is_word = true;    }    bool search(string word) {        Node x = root;        int p = 0;        while (x.next && p < word.size())            x = x.next[word[p++] - 'a'];        return p == word.size() && x.is_word;    }    bool startsWith(string prefix) {        Node x = root;        int p = 0;        while (x.next && p < prefix.size())            x = x.next[prefix[p++] - 'a'];        return p == prefix.size() && (x.next || x.is_word);    }private:    Node root;};

原创粉丝点击