211. 添加与搜索单词 - 数据结构设计

211. 添加与搜索单词 - 数据结构设计


题目链接:211. 添加与搜索单词 - 数据结构设计

代码如下:

cpp 复制代码
//前缀树 参考leetcode官方题解
class TrieNode {
public:
    vector<TrieNode*> children;
    bool isEnd;
    TrieNode() : children(26), isEnd(false) {}
};

class WordDictionary {
private:
    TrieNode* trie;
    void insert(TrieNode* root, const string& word) {
        TrieNode* node = root;
        for (int i = 0; i < word.size(); i++) {
            if (node->children[word[i] - 'a'] == nullptr)
                node->children[word[i] - 'a'] = new TrieNode();
            node = node->children[word[i] - 'a'];
        }
        node->isEnd = true;
    }

    //深度遍历
    bool dfs(const string& word, int index, TrieNode* node) {
        if (index ==
            word.size()) //如果到了单词的末尾。看看前缀树是否到达单词末尾
            return node->isEnd;
        if (word[index] >= 'a' && word[index] <= 'z') { //如果是字母,就继续查找
            TrieNode* child = node->children[word[index] - 'a'];
            if (child != nullptr && dfs(word, index + 1, child))
                return true;
        } else if (word[index] ==
                   '.') { //如果是.,就把26个字母都查找一遍进行匹配
            for (int i = 0; i < 26; i++) {
                TrieNode* child = node->children[i];
                if (child && dfs(word, index + 1, child))
                    return true;
            }
        }
        return false;
    }

public:
    WordDictionary() { trie = new TrieNode(); }

    void addWord(string word) { insert(trie, word); }

    bool search(string word) { return dfs(word, 0, trie); }
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */
相关推荐
位东风22 分钟前
【c++学习记录】状态模式,实现一个登陆功能
c++·学习·状态模式
雷羿 LexChien2 小时前
C++内存泄漏排查
开发语言·c++
嘉小华3 小时前
CMake 完全指南:第一章 - 构建的烦恼 - 为什么需要CMake?
c++
Feliz Da Vida3 小时前
[代码学习] c++ 通过H矩阵快速生成图像对应的mask
c++·学习
无聊的小坏坏4 小时前
单调栈通关指南:从力扣 84 到力扣 42
c++·算法·leetcode
YOLO大师5 小时前
华为OD机试 2025B卷 - 小明减肥(C++&Python&JAVA&JS&C语言)
c++·python·华为od·华为od机试·华为od2025b卷·华为机试2025b卷·华为od机试2025b卷
看到我,请让我去学习6 小时前
OpenCV编程- (图像基础处理:噪声、滤波、直方图与边缘检测)
c语言·c++·人工智能·opencv·计算机视觉
xiaolang_8616_wjl15 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
夜月yeyue15 小时前
设计模式分析
linux·c++·stm32·单片机·嵌入式硬件
无小道15 小时前
c++-引用(包括完美转发,移动构造,万能引用)
c语言·开发语言·汇编·c++