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);
 */
相关推荐
迷迭所归处6 小时前
C++ —— 关于vector
开发语言·c++·算法
CV工程师小林6 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
white__ice7 小时前
2024.9.19
c++
天玑y7 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
姜太公钓鲸2337 小时前
c++ static(详解)
开发语言·c++
菜菜想进步7 小时前
内存管理(C++版)
c语言·开发语言·c++
Joker100858 小时前
C++初阶学习——探索STL奥秘——模拟实现list类
c++
科研小白_d.s8 小时前
vscode配置c/c++环境
c语言·c++·vscode
湫兮之风8 小时前
c++:tinyxml2如何存储二叉树
开发语言·数据结构·c++
友友马9 小时前
『 Linux 』HTTP(一)
linux·运维·服务器·网络·c++·tcp/ip·http