Leecode Hot100 刷题笔记本-字典树(C++版)

32 阅读1分钟
  1. 208. 实现 Trie (前缀树)

208. 实现 Trie (前缀树)

Screen Shot 2023-08-31 at 5.54.48 PM.png Screen Shot 2023-08-31 at 6.11.36 PM.png

class Trie {
private:
    vector<Trie*> children; // 存储子节点的数组,长度为26,用于表示26个小写字母
    bool isEnd; // 标志当前节点是否是一个字符串的结束节点

    // 私有方法,用于查找以指定前缀开头的节点
    Trie* searchPrefix(string prefix) {
        Trie* node = this;
        for (char ch : prefix) {
            ch -= 'a'; // 将字符映射到0到25的范围
            if (node->children[ch] == nullptr) {
                return nullptr; // 如果当前节点的子节点中没有匹配的字符,返回nullptr
            }
            node = node->children[ch]; // 否则,继续向下遍历
        }
        return node; // 返回以指定前缀开头的节点
    }

public:
    // 构造函数,初始化Trie树的根节点,包括子节点数组和isEnd标志
    Trie() : children(26), isEnd(false) {}

    // 插入一个字符串到Trie树中
    void insert(string word) {
        Trie* node = this; // 从根节点开始
        for (char ch : word) {
            ch -= 'a'; // 将字符映射到0到25的范围
            if (node->children[ch] == nullptr) {
                node->children[ch] = new Trie(); // 如果当前字符的子节点为空,创建一个新的子节点
            }
            node = node->children[ch]; // 继续向下遍历
        }
        node->isEnd = true; // 在最后一个字符节点上标记为字符串结束
    }

    // 搜索一个完整的字符串是否存在于Trie树中
    bool search(string word) {
        Trie* node = this->searchPrefix(word); // 先查找以指定前缀开头的节点
        return node != nullptr && node->isEnd; // 如果找到节点且isEnd为true,表示字符串存在
    }

    // 检查Trie树中是否有以指定前缀开头的字符串
    bool startsWith(string prefix) {
        return this->searchPrefix(prefix) != nullptr; // 查找以指定前缀开头的节点是否存在
    }
};

Screen Shot 2023-08-31 at 6.10.13 PM.png