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);
 */
相关推荐
程序员zgh2 分钟前
常用通信协议介绍(CAN、RS232、RS485、IIC、SPI、TCP/IP)
c语言·网络·c++
暗然而日章12 分钟前
C++基础:Stanford CS106L学习笔记 8 继承
c++·笔记·学习
有点。30 分钟前
C++ ⼀级 2023 年06 ⽉
开发语言·c++
charlie11451419132 分钟前
编写INI Parser 测试完整指南 - 从零开始
开发语言·c++·笔记·学习·算法·单元测试·测试
mmz120737 分钟前
前缀和问题2(c++)
c++·算法
Alpha first1 小时前
C++核心知识点梳理:类型兼容、多继承与虚基类
开发语言·c++
.小小陈.1 小时前
C++初阶9:list使用攻略
开发语言·c++·学习·list
天赐学c语言2 小时前
12.14 - 搜索旋转排序数组 && 判断两个结构体是否相等
数据结构·c++·算法·leecode
超自然祈祷2 小时前
水声相关公式C++实现
开发语言·c++
仰泳的熊猫2 小时前
1112 Stucked Keyboard
数据结构·c++·算法·pat考试