hot100:前缀树

前缀树多用于前缀搜索,每个节点最多包含26个指向下一个节点的指针

class Trie {
private:
    bool isEnd;
    // 可以存放26个指针
    Trie* next[26];

public:
    Trie() {
        isEnd = false;
        for (int i = 0; i < 26; ++i) {
            next[i] = NULL;
        }
    }

    void insert(string word) {
        Trie* node = this;
        for (char c : word) {
            if (node->next[c - 'a'] == NULL) {
                node->next[c - 'a'] = new Trie();
            }
            node = node->next[c - 'a'];
        }
        node->isEnd = true;
    }

    bool search(string word) {
        Trie* node = this;
        for (char c : word) {
            node = node->next[c - 'a'];
            if (node == NULL) {
                return false;
            }
        }
        return node->isEnd;
    }

    bool startsWith(string prefix) {
        Trie* node = this;
        for (char c : prefix) {
            node = node->next[c - 'a'];
            if (node == NULL) {
                return false;
            }
        }
        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);
 */
posted @ 2025-02-16 11:49  huigugu  阅读(2)  评论(0编辑  收藏  举报