|
| 1 | +structTrieNode { |
| 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 | +classWordDictionary { |
| 12 | +private: |
| 13 | +TrieNode* root; |
| 14 | +public: |
| 15 | +WordDictionary() { |
| 16 | +root =new TrieNode; |
| 17 | +} |
| 18 | + |
| 19 | +voidaddWord(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 | +boolrecursiveSearch(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 | +returntrue; |
| 45 | +} |
| 46 | +// search with backtracking failed in all children |
| 47 | +returnfalse; |
| 48 | +} |
| 49 | +else { |
| 50 | +// simple trie search |
| 51 | +int idx = word[i] -'a'; |
| 52 | +if (cur->children[idx] ==nullptr) |
| 53 | +returnfalse; |
| 54 | +cur = cur->children[idx]; |
| 55 | +} |
| 56 | +} |
| 57 | +// check if the node is end of any word |
| 58 | +return cur->isWordEnd; |
| 59 | +} |
| 60 | + |
| 61 | +boolsearch(string word) { |
| 62 | +returnrecursiveSearch(word,0, root); |
| 63 | +} |
| 64 | +}; |