struct TreeNode26 { char val; TreeNode26* next[26]; bool isLast = false; TreeNode26(char v) { val = v; for (int i = 1; i <= 26; i++) { next[i - 1] = NULL; } } bool hasChild26() { for (int i = 1; i <= 26; i++) { if (next[i - 1]) return true; } return false; } }; class WordDictionary { public: /** Initialize your data structure here. */ TreeNode26 *root; WordDictionary() { root = new TreeNode26(' '); }
/** Adds a word into the data structure. */ void addWord(string word) { int size = word.size(); TreeNode26 *node = root; for (int i = 1; i <= size; i++) { int pos = word[i - 1] - 'a'; if (node->next[pos] == NULL) { node->next[pos] = new TreeNode26(word[i - 1]); } node = node->next[pos]; } node->isLast = true; }
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ bool search(string word) { data = word; return DFS(root, 0); } bool DFS(TreeNode26 *node ,int pos) { char ch = data[pos]; if (pos == int(data.size())) { return node->isLast; } if (ch == '.') { for (int i = 1; i <= 26; i++) { if (node->next[i - 1]&&DFS(node->next[i - 1], pos + 1)) return true; } return false; } else { if (node->next[ch - 'a']) return DFS(node->next[ch - 'a'], pos + 1); return false; } } string data; };