1、本题与先前的Trie树相比,最大的差别就在引入了对通配符".“的处理。但由于引入此,就需要在出现”."的同一节点分支全部进行搜索,才能不漏掉所有可能。
2、搜索采用递归较好。
class WordDictionary {
private:
struct TNode{
char key;
map<char, TNode*> node;
int count;
TNode(char letter):key(letter), count(0){}
};
TNode* rootPtr;
//use last node and current string
bool reccurrentSearch(TNode* lastPtr, string str){
TNode* searchPtr = lastPtr;
int strLen = str.length();
if(!strLen && lastPtr->count){
return true;
}
for(int i = 0; i < strLen; i++){
char ch = str[i];
if(ch == '.'){
bool flag = 0;
string remainWord;
remainWord.assign(str.begin()+i+1, str.end());
for(auto it:searchPtr->node){
flag |= reccurrentSearch(it.second, remainWord);
if(flag)
return true;
}
if(!flag)
return false;
}else{
auto it = searchPtr->node.find(ch);
if(it == searchPtr->node.end()){
return false;
}
searchPtr = it->second;
}
}
if(searchPtr->count)
return true;
return false;
}
public:
/** Initialize your data structure here. */
WordDictionary() {
rootPtr = new TNode(0);
}
/** Adds a word into the data structure. */
void addWord(string word) {
TNode* innerPtr = rootPtr;
for(auto ch:word){
auto it = innerPtr->node.find(ch);
if(it == innerPtr->node.end()){
innerPtr->node[ch] = new TNode(ch);
innerPtr = innerPtr->node[ch];
}else{
innerPtr = it->second;
}
}
innerPtr->count++;
}
/** 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 reccurrentSearch(rootPtr, word);
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/