实现代码如下所示:
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;
}