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);
 */
相关推荐
choumin18 分钟前
C++中std::move和std::forward的关系和区别
c++·std move·std forward·关系和区别
程序猿编码23 分钟前
YOLOv5/v7/YOLOX 全支持:基于 TensorRT 的工业视觉推理底座详解
c++·yolo·机器学习·推理·模型推理
kyle~31 分钟前
C++ 原子操作、内存模型与无锁并发编程
linux·开发语言·c++·操作系统
another heaven34 分钟前
【C/C++ C++ 面向对象架构的五大特点与能力场景:封装、继承、多态、抽象与 RAII(含实战案例)】
c语言·c++·架构
努力努力再努力wz1 小时前
【C++ 高阶系列】C++ 高性能网络编程:当 Reactor 遇见协程:从 epoll 回调到异步 MySQL,彻底打通任务挂起与恢复
网络·c++·mysql
霍霍的袁2 小时前
【C++11】左值右值引用与移动语义详细笔记(左值右值、右值引用、移动构造、移动赋值、引用折叠、万能转发)
c++·笔记·学习·visual studio
布莱克6052 小时前
C++ 中 unordered_set 与 unordered_map 有什么不同?一篇讲透
开发语言·c++·哈希
鶴哥只手遮天3 小时前
AFSIM 2.9.0 深度解析:架构、原理与工程实践-第 1 章 项目全景与代码地图
c++
充值内卷3 小时前
C++单文件迷宫游戏:TauriCPP 开发全记录
开发语言·c++·游戏
Antruly3 小时前
C++ Web 开发选型漫谈:从 Drogon 到 libuvcpp + uvp,八个项目的定位、兼容性与务实排名
开发语言·前端·c++