map<string, int> datas; // Adds a word into the data structure. voidaddWord(string word){ auto it = datas.find(word); if (it == datas.end()) { pair<string, int> p(word, 1); datas.insert(p); } else { it->second += 1; } }
// Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. boolsearch(string word){ bool r = false; string st; solve(r, st, word, 0); return r; }
voidsolve(bool& r, string& st, string& word, int index) { int pos = index; for (; pos < word.length(); ++pos) { if (word[pos] == '.') { break; } st.push_back(word[pos]); }
if (st.length() == word.length()) { if (r == false) { r = (datas.find(st) != datas.end()); } return; }
for (int i = 'a'; i <= 'z'; ++i) { st.push_back((char)i); solve(r, st, word, pos + 1); if (r) return; int l = st.length() - pos; while (l > 0) { st.pop_back(); --l; } } } };
struct Node { char c; bool bstr; Node* children[26]; Node() { for (int i = 0; i < 26; ++i) children[i] = NULL; bstr = false; } Node(char ch):c(ch) { for (int i = 0; i < 26; ++i) children[i] = NULL; bstr = false; } }root; // Adds a word into the data structure. voidaddWord(string word){ Node* pRoot = &root; for (int i = 0; i < word.length(); ++i) { if (pRoot->children[word[i] - 'a'] == NULL) { pRoot->children[word[i] - 'a'] = new Node(word[i]); } pRoot = pRoot->children[word[i] - 'a']; if (i + 1 == word.length()) pRoot->bstr = true; } }
intcheck(string& s) { Node* pRoot = &root; Node* eNode = NULL; for (int i = 0; i < s.length(); ++i) { pRoot = pRoot->children[s[i] - 'a']; if (pRoot == NULL) return0; if (i + 1 == s.length()) eNode = pRoot; } if (eNode->bstr) return1; return -1; }
// Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. boolsearch(string word){ bool r = false; string st; solve(r, st, word, 0); return r; }
voidsolve(bool& r, string& st, string& word, int index) { int pos = index; for (; pos < word.length(); ++pos) { if (word[pos] == '.') { break; } st.push_back(word[pos]); }
if (st.length() == word.length()) { if (r == false) { r = (1 == check(st)); } return; }
for (int i = 'a'; i <= 'z'; ++i) { st.push_back((char)i); if (0 == check(st)) { st.pop_back(); continue; } solve(r, st, word, pos + 1); if (r) return; int l = st.length() - pos; while (l > 0) { st.pop_back(); --l; } } } };