Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
implement-magic-dictionary.cpp 2.41 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-09-10 15:01 +08:00 . Create implement-magic-dictionary.cpp
// Time: O(n), n is the length of the word
// Space: O(d)
class MagicDictionary {
public:
/** Initialize your data structure here. */
MagicDictionary() {
}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) {
string result;
for (const auto& s : dict) {
trie_.Insert(s);
}
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
bool search(string word) {
return find(word, &trie_, 0, true);
}
private:
struct TrieNode {
bool isString = false;
unordered_map<char, TrieNode *> leaves;
void Insert(const string& s) {
auto* p = this;
for (const auto& c : s) {
if (p->leaves.find(c) == p->leaves.cend()) {
p->leaves[c] = new TrieNode;
}
p = p->leaves[c];
}
p->isString = true;
}
~TrieNode() {
for (auto& kv : leaves) {
if (kv.second) {
delete kv.second;
}
}
}
};
bool find(const string& word, TrieNode *curr, int i, bool mistakeAllowed) {
if (i == word.length()) {
return curr->isString && !mistakeAllowed;
}
if (!curr->leaves.count(word[i])) {
return mistakeAllowed ?
any_of(curr->leaves.begin(), curr->leaves.end(),
[&](const pair<char, TrieNode *>& kvp) {
return find(word, kvp.second, i + 1, false);
}) :
false;
}
if (mistakeAllowed) {
return find(word, curr->leaves[word[i]], i + 1, true) ||
any_of(curr->leaves.begin(), curr->leaves.end(),
[&](const pair<char, TrieNode *>& kvp) {
return kvp.first != word[i] && find(word, kvp.second, i + 1, false);
});
}
return find(word, curr->leaves[word[i]], i + 1, false);
}
TrieNode trie_;
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dict);
* bool param_2 = obj.search(word);
*/
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助