1 Star 0 Fork 0

wilson3123/go-leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
add_and_search_word.cpp 1.40 KB
一键复制 编辑 原始数据 按行查看 历史
zczou 提交于 9年前 . solve 4 problems
#include <unordered_map>
using namespace std;
struct TrieNode {
bool is_word_;
unordered_map<char, TrieNode*> children;
TrieNode(): is_word_(false) {}
};
class WordDictionary {
public:
TrieNode* root;
WordDictionary() {
root = new TrieNode();
}
// Adds a word into the data structure.
void addWord(string word) {
if (word.size() <= 0) return;
TrieNode* node = root;
for (int i = 0; i < word.size(); ++i){
if (node->children.find(word[i]) == node->children.end()){
node->children[word[i]] = new TrieNode();
}
node = node->children[word[i]];
}
node->is_word_ = true;
}
// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
bool search(string word) {
return retrieve(word, root, 0, word.size());
}
bool retrieve(string& word, TrieNode* node, int idx, int length) {
if (idx == length) return node->is_word_;
if (word[idx] == '.') {
if (node->children.size() == 0) {
return false;
}
for (auto& kv: node->children) {
if (retrieve(word, kv.second, idx+1, length)) {
return true;
}
}
return false;
}else if (node->children.find(word[idx]) != node->children.end()) {
return retrieve(word, node->children[word[idx]], idx+1, length);
}
return false;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/wilson3123/go-leetcode.git
git@gitee.com:wilson3123/go-leetcode.git
wilson3123
go-leetcode
go-leetcode
master

搜索帮助