程式語言 - LeetCode - C++ - 208. Implement Trie (Prefix Tree)



參考資訊:
https://algo.monster/liteproblems/208
https://www.cnblogs.com/grandyang/p/4491665.html

題目:


方法:


解答:

class Trie {
private:
    vector<Trie *> child;
    bool is_word;

public:
    Trie() : child(26, nullptr), is_word(false) {
    }
    
    void insert(string word) {
        Trie *p = this;

        for (char ch:  word) {
            int idx = ch - 'a';

            if (p->child[idx] == nullptr) {
                p->child[idx] = new Trie();
            }
            p = p->child[idx];
        }
        p->is_word = true;
    }
    
    bool search(string word) {
        Trie *p = this;

        for (char ch:  word) {
            int idx = ch - 'a';

            if (p->child[idx] == nullptr) {
                return false;
            }
            p = p->child[idx];
        }

        return p->is_word;
    }
    
    bool startsWith(string prefix) {
        Trie *p = this;

        for (char ch:  prefix) {
            int idx = ch - 'a';

            if (p->child[idx] == nullptr) {
                return false;
            }
            p = p->child[idx];
        }

        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);
 */