设计一个支持以下两种操作的数据结构:
void addWord(word)
bool search(word)
search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
示例:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
说明:
你可以假设所有单词都是由小写字母 a-z 组成的。
解题
添加前缀树结构,插入树;
查找树时进行递归判断,若当前处理字符为’.'则需要尝试next每一个可行的下标;
class trie{
public:
string word="";
vector<trie*> next;
trie():next(26,0){}
};
class WordDictionary {
private:
trie TREE;
public:
/** Initialize your data structure here. */
WordDictionary() {
}
/** Adds a word into the data structure. */
void addWord(string word) {
trie* tmp=&TREE;
for(char c:word)
{
if(!tmp->next[c-'a']) tmp->next[c-'a']=new trie;
tmp=tmp->next[c-'a'];
}
tmp->word=word;
}
int n;
/** 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) {
n=word.size();
trie* tmp=&TREE;
return traceback(word,0,tmp);
}
bool traceback(string word,int curi,trie* root){
if(curi==n) return root->word!=""; //突然成功
trie* tmp=root;
if(word[curi]!='.'){
if(tmp->next[word[curi]-'a'])
return traceback(word,curi+1,tmp->next[word[curi]-'a']);
}
else { //为'.'
for(int i=0;i<26;i++)
{
if(tmp->next[i]&&traceback(word,curi+1,tmp->next[i]))
return true;
}
return false;
}
return false;
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/
注意点
curi从0开始,而递归从空trie开始,故curi==word.size()时才为结束条件;