本题源自 leetcode 211
--------------------------------------------------------------------------------
思路:用一个单词查找树结构 Trie.添加单词就是把这个单词添加到字典中,然后a设置-z子串。
搜索,就在trie中搜素,如果不是正则匹配,就在其子串中搜素,否则递归匹配。
代码:
class Trie{
public:
bool isKey;
Trie* children[26];
Trie(){
isKey = false;
memset(children,NULL,sizeof(Trie*) * 26);
}
};
class WordDictionary {
public:
/** Initialize your data structure here. */
WordDictionary() {
root = new Trie();
}
/** Adds a word into the data structure. */
void addWord(string word) {
Trie * node = root;
for(char c : word){
if(!node->children[c - 'a'])
node->children[c - 'a'] = new Trie();
node = node->children[c - 'a'];
}
node->isKey = 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) {
return query(word.c_str(),root);
}
private:
Trie* root;
bool query(const char* word,Trie* root){
Trie* node = root;
for(int i = 0; word[i]; i++){
if(node && word[i] != '.'){
node = node->children[word[i] - 'a'];
}else if(node && word[i] == '.'){
Trie* tmp = node;
for(int j = 0; j < 26; j++){
node = tmp->children[j];
if(query(word + i + 1, node))
return true;
}
}
else
break;
}
return node && node->isKey;
}
};