|
| 1 | +struct TrieNode { |
| 2 | + TrieNode* children[26]; |
| 3 | + bool isWordEnd; |
| 4 | + |
| 5 | + TrieNode() : isWordEnd(false) { |
| 6 | + for (int i = 0; i < 26; ++i) |
| 7 | + children[i] = nullptr; |
| 8 | + } |
| 9 | +}; |
| 10 | + |
| 11 | +class WordDictionary { |
| 12 | +private: |
| 13 | + TrieNode* root; |
| 14 | +public: |
| 15 | + WordDictionary() { |
| 16 | + root = new TrieNode; |
| 17 | + } |
| 18 | + |
| 19 | + void addWord(string word) { |
| 20 | + // simple trie insertion |
| 21 | + TrieNode* cur = root; |
| 22 | + |
| 23 | + int idx; |
| 24 | + for (int i = 0; i < word.size(); ++i) { |
| 25 | + idx = word[i] - 'a'; |
| 26 | + if (cur->children[idx] == nullptr) |
| 27 | + cur->children[idx] = new TrieNode; |
| 28 | + cur = cur->children[idx]; |
| 29 | + } |
| 30 | + // mark the last node as end of a word |
| 31 | + cur->isWordEnd = true; |
| 32 | + } |
| 33 | + |
| 34 | + bool recursiveSearch(const string &word, int curIdx, const TrieNode *node) { |
| 35 | + auto cur = node; |
| 36 | + |
| 37 | + for (int i = curIdx; i < word.size(); ++i) { |
| 38 | + if (word[i] == '.') { |
| 39 | + // can match any character - backtracking is required |
| 40 | + for (int j = 0; j < 26; ++j) { |
| 41 | + if (cur->children[j] == nullptr) // skip non-existing characters |
| 42 | + continue; |
| 43 | + if (recursiveSearch(word, i + 1, cur->children[j])) // try and backtrack if fails |
| 44 | + return true; |
| 45 | + } |
| 46 | + // search with backtracking failed in all children |
| 47 | + return false; |
| 48 | + } |
| 49 | + else { |
| 50 | + // simple trie search |
| 51 | + int idx = word[i] - 'a'; |
| 52 | + if (cur->children[idx] == nullptr) |
| 53 | + return false; |
| 54 | + cur = cur->children[idx]; |
| 55 | + } |
| 56 | + } |
| 57 | + // check if the node is end of any word |
| 58 | + return cur->isWordEnd; |
| 59 | + } |
| 60 | + |
| 61 | + bool search(string word) { |
| 62 | + return recursiveSearch(word, 0, root); |
| 63 | + } |
| 64 | +}; |
0 commit comments