} else if (c == '.') {
? ? for (int i = 0; i < 26; i++) {
? ? ? ? TrieNode* child = node->child[i];
? ? ? ? if (child != nullptr && dfs(word, index + 1, child)) {
? ? ? ? ? ? return true;
? ? ? ? }
? ? }
}
struct TrieNode {
std::vector<TrieNode*> child;
bool isEnd;
TrieNode() :
child(std::vector<TrieNode*>(26, nullptr)) ,
isEnd(false) {
}
};
void insert(TrieNode* root, const std::string& word) {
TrieNode* node = root;
for (auto c : word) {
if (node->child[c - 'a'] == nullptr) {
node->child[c - 'a'] = new TrieNode();
}
node = node->child[c - 'a'];
}
node->isEnd = true;
}
class WordDictionary {
public:
WordDictionary() {
tire = new TrieNode();
}
void addWord(string word) {
insert(tire, word);
}
bool search(string word) {
return dfs(word, 0, tire);
}
private:
bool dfs(const std::string& word, int index, TrieNode* node) {
if (index == word.size()) {
return node->isEnd;
}
char c = word[index];
if (c >= 'a' && c <= 'z') {
TrieNode* child = node->child[c - 'a'];
if (child != nullptr && dfs(word, index + 1, child)) {
return true;
}
} else if (c == '.') {
for (int i = 0; i < 26; i++) {
TrieNode* child = node->child[i];
if (child != nullptr && dfs(word, index + 1, child)) {
return true;
}
}
}
return false;
}
private:
TrieNode* tire;
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/
————————————————————————————