LeetCode 211. Add and Search Word - Data structure design(字典树)
字典树。
class WordDictionary {
public:
int map[100005][26];
int tag[100005];
int num;
/** Initialize your data structure here. */
WordDictionary() {
memset(map,0,sizeof(map));
memset(tag,0,sizeof(tag));
num=0;
}
/** Adds a word into the data structure. */
void addWord(string word) {
Add(word,0,0);
}
void Add(string word,int i,int pos)
{
if(i==word.length())
{
tag[pos]=1;
return;
}
if(map[pos][word[i]-'a']==0)
{
map[pos][word[i]-'a']=++num;
}
Add(word,i+1,map[pos][word[i]-'a']);
}
/** 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 SearchWord(word,0,0);
}
bool SearchWord(string word,int i,int pos)
{
if(i==word.length())
{
if(tag[pos]==1)
return true;
else
return false;
}
if(word[i]=='.')
{
for(int j=0;j<26;j++)
{
if(map[pos][j]!=0)
{
bool ans = SearchWord(word,i+1,map[pos][j]);
if(ans==true)
return true;
}
}
return false;
}
else
{
if(map[pos][word[i]-'a']==0)
{
return false;
}
else
{
return SearchWord(word,i+1,map[pos][word[i]-'a']);
}
}
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/