题目是 LeetCode 211: https://leetcode.com/problems/add-and-search-word-data-structure-design/description/
我提交代码之后,发现是第一个 test case 错误(下图中红色下划线处),正确答案为 true,而我输出了 false,如下图:
但是当我在本地 Visual Studio 里调试的时候,发现对于这个 test case 的输出确实是 true
本人百思不得其解。。。特来求助
我的代码如下:
#include <string>
#include <unordered_map>
using namespace std;
struct TrieNode {
unordered_map<char, TrieNode*> next;
bool is_word;
TrieNode() : is_word(false) {}
};
class WordDictionary {
public:
/** Initialize your data structure here. */
WordDictionary() {
root = new TrieNode();
}
/** Adds a word into the data structure. */
void addWord(string word) {
TrieNode* curr = root;
for (char c : word) {
if (curr->next.find(c) == curr->next.end()) {
curr->next[c] = new TrieNode();
}
curr = curr->next[c];
}
curr->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) {
TrieNode* node = dfs(word, 0, root);
return node != NULL && node->is_word;
}
private:
TrieNode * root;
TrieNode * dfs(string& target, int index, TrieNode* curr) {
if (index == target.size()) {
return curr;
}
char c = target[index];
if (c == '.') {
for (auto it = curr->next.begin(); it != curr->next.end(); ++it) {
TrieNode* found = dfs(target, index + 1, it->second);
if (found != NULL) {
return found;
}
}
return NULL;
}
auto it = curr->next.find(c);
return it == curr->next.end() ? NULL : dfs(target, index + 1, it->second);
}
};
int main() {
WordDictionary wd;
bool r;
wd.addWord("ran");
wd.addWord("rune");
wd.addWord("runner");
wd.addWord("runs");
wd.addWord("add");
wd.addWord("adds");
wd.addWord("adder");
wd.addWord("addee");
r = wd.search("r.n"); // true
r = wd.search("ru.n.e"); // false
r = wd.search("add"); // true
r = wd.search("add."); // true
r = wd.search("adde."); // true
r = wd.search(".an."); // false
r = wd.search("...s"); // true
r = wd.search("....e."); // true
r = wd.search("......."); // false
r = wd.search("..n.r"); // false
return 0;
}