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);
 */
相关推荐
mit6.8242 小时前
[openvela] Hello World :从零开始的完整实践与问题复盘
c++·嵌入式硬件
啊阿狸不会拉杆4 小时前
《算法导论》第 32 章 - 字符串匹配
开发语言·c++·算法
小学生的信奥之路4 小时前
洛谷P3817题解:贪心算法解决糖果分配问题
c++·算法·贪心算法
曙曙学编程5 小时前
stm32——GPIO
c语言·c++·stm32·单片机·嵌入式硬件
△曉風殘月〆5 小时前
Visual Studio中的常用调试功能(下)
c++·ide·visual studio·调试
武当豆豆5 小时前
C++编程学习(第25天)
开发语言·c++·学习
minji...9 小时前
C++ string类(STL简介 , string类 , 访问修改字符)
开发语言·c++
Forward♞9 小时前
Qt——文件操作
开发语言·c++·qt
十五年专注C++开发9 小时前
CMake进阶: CMake Modules---简化CMake配置的利器
linux·c++·windows·cmake·自动化构建
winds~10 小时前
【git】 撤销revert一次commit中的某几个文件
linux·c++