Design Add and Search Words Data Structure LeetCode solution in C++
1class WordDictionary {2public:3struct tr {4bool isword;5vector<tr *> next;6tr() {7next.resize(26, NULL);8isword = false;9}10};1112tr *root;13WordDictionary() {14root = new tr();15}1617void addWord(string word) {18tr *cur = root;1920for (auto c : word) {21if (cur->next[c - 'a'] == NULL) {22cur->next[c - 'a'] = new tr();23}24cur = cur->next[c - 'a'];25}2627cur->isword = true;28}2930bool dfs(string &word, int i, tr *cur) {31if (!cur) {32return false;33}3435if (i == word.size()) {36return cur->isword;37}3839for (; i < word.size(); i++) {40char c = word[i];41if (c == '.') {42for (auto it : cur->next) {43if (dfs(word, i + 1, it)) {44return true;45}46}47return false;48} else {49if (cur->next[c - 'a'] == NULL) {50return false;51}52cur = cur->next[c - 'a'];53}54}5556return cur->isword;57}5859bool search(string word) {60return dfs(word, 0, root);61}62};6364/**65* Your WordDictionary object will be instantiated and called as such:66* WordDictionary* obj = new WordDictionary();67* obj->addWord(word);68* bool param_2 = obj->search(word);69*/