数据结构-前缀树(Trie)

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

实现代码如下所示:

cpp 复制代码
#include <bits/stdc++.h>  // 包含标准库所有头文件
using namespace std;      // 使用标准命名空间

class WordDictionary {
public:
    WordDictionary() = default;  // 默认构造函数,root已在声明处初始化

    // 添加单词到字典树
    void addWord(const string& word) {
        TrieNode* node = root;  // 从根节点开始遍历
        
        for (char ch : word) {  // 遍历单词的每个字符
            // 如果当前字符的子节点不存在,则创建新节点
            if (node->children.find(ch) == node->children.end()) {
                node->children[ch] = new TrieNode();
            }
            node = node->children[ch];  // 移动到子节点继续
        }
        node->isEnd = true;  // 标记单词结束位置
    }

    // 搜索单词(支持通配符'.')
    bool search(const string& word) {
        // 从位置0和根节点开始递归搜索
        return searchInNode(word, 0, root);
    }

private:
    // 字典树节点结构
    struct TrieNode {
        unordered_map<char, TrieNode*> children;  // 使用哈希表存储子节点,节省空间
        bool isEnd = false;  // 标记是否为某个单词的结尾
    };

    TrieNode* root = new TrieNode();  // 字典树的根节点

    // 递归搜索辅助函数
    bool searchInNode(const string& word, int pos, TrieNode* node) {
        if (!node) return false;  // 节点不存在,匹配失败
        
        // 已经处理完整个单词,检查当前节点是否为单词结尾
        if (pos == word.size()) return node->isEnd;

        char ch = word[pos];  // 获取当前位置的字符
        
        if (ch == '.') {
            // 通配符:需要尝试所有可能的子节点
            for (auto& [key, child] : node->children) {
                // 对每个子节点递归搜索剩余部分
                if (searchInNode(word, pos + 1, child)) {
                    return true;  // 只要有一个分支匹配就成功
                }
            }
            return false;  // 所有分支都失败
        } else {
            // 普通字符:查找对应的子节点
            auto it = node->children.find(ch);
            if (it == node->children.end()) return false;  // 字符不存在,匹配失败
            
            // 继续匹配下一个字符
            return searchInNode(word, pos + 1, it->second);
        }
    }
};


int main() {
    WordDictionary wordDictionary;
    wordDictionary.addWord("bad");
    wordDictionary.addWord("dad");
    wordDictionary.addWord("mad");

    cout << boolalpha;
    cout << wordDictionary.search("pad") << endl; // false
    cout << wordDictionary.search("bad") << endl; // true
    cout << wordDictionary.search(".ad") << endl; // true
    cout << wordDictionary.search("b..") << endl; // true
    cout << wordDictionary.search(".a..") << endl; // false (长度不匹配自动剪枝)

    return 0;
}
相关推荐
励志不掉头发的内向程序员1 小时前
【LibreCAD 2D架构】从两个坐标到图形实体:RS_ActionDrawLine如何创建RS_Line
开发语言·c++·qt·学习·系统架构
Thomas21431 小时前
scala 闭包
开发语言·后端·scala
sunshine22 girl1 小时前
Java学习一 环境配置1 安装JDK,配置环境变量
java·开发语言·学习
似水এ᭄往昔1 小时前
【Qt】--常用控件(按钮类控件)
开发语言·qt
张人玉2 小时前
基于 C# WinForms + .NET 8 + SQLite + TCP Socket 的多连接通讯调试工具——TCP通讯助手(TcpAssistant)
tcp/ip·sqlite·c#·.net
范什么特西2 小时前
一些常用名词
开发语言·前端·javascript
吴声子夜歌2 小时前
ApacheCommons——commons-configuration2(多数据源配置统一管理与热加载)
java·开发语言·算法·apache
乌夷2 小时前
JavaScript 的事件循环
开发语言·javascript·ecmascript
星星落进兜里2 小时前
Java虚拟机面试题-补充
java·开发语言