1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| class WordDictionary { struct TrieNode { TrieNode *children[26] = {nullptr}; bool isEnd = false; };
TrieNode *root = nullptr;
public: WordDictionary() : root(new TrieNode) {
}
void addWord(string word) { auto p = root; for (auto c : word) { int k = c - 'a'; if (!p->children[k]) { p->children[k] = new TrieNode; } p = p->children[k]; } p->isEnd = true; }
bool search(string word) { return search(word, 0, root); }
bool search(const string &w, int i, TrieNode *p) { if (!p) return false; if (i == w.length()) return p->isEnd; if (w[i] != '.') return search(w, i + 1, p->children[w[i] - 'a']); for (int k = 0; k < 26; ++k) { if (search(w, i + 1, p->children[k])) return true; } return false; } };
|