借用Trie树,addword就是insert,搜索的时候因为有’.’的存在,用递归dfs的思路
#define cti(x) (x-'a')
#define itc(x) (x+'a')
const int maxn = 70005;
const int sigma_size = 26;
class WordDictionary {
public:
/** Initialize your data structure here. */
int ch[maxn][sigma_size], val[maxn] = {}, sz;
WordDictionary() {
sz = 1, memset(ch[0], 0, sizeof(ch[0]));
}
/** Adds a word into the data structure. */
void addWord(string word) {
int o = 0;
for (int i = 0; i < word.size(); ++i) {
if (!ch[o][cti(word[i])])
memset(ch[sz], 0, sizeof(ch[sz])), val[sz] = 0, ch[o][cti(word[i])] = sz++;
o = ch[o][cti(word[i])];
}
val[o] = 1;
}
/** 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, int index, int o) {
if (index == word.size()) return val[o];
if (word[index] != '.') {
if (ch[o][cti(word[index])])return search(word, index + 1, ch[o][cti(word[index])]);
else return false;
}
for (int i = 0; i<sigma_size; ++i)
if (ch[o][i] && search(word, index + 1, ch[o][i])) return true;
return false;
}
bool search(string word) {
return search(word, 0, 0);
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* bool param_2 = obj.search(word);
*/