数据结构:字典树
1.题目:
设计一个支持以下两种操作的数据结构:
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
2.代码:
#define MAXN 30
typedef struct WordDictionary{
bool end;
struct WordDictionary* next[MAXN];
}WordDictionary;
/** Initialize your data structure here. */
WordDictionary* wordDictionaryCreate() {
WordDictionary* tree=(WordDictionary* )malloc(sizeof(WordDictionary));
tree->end=false;
for(int i=0;i<MAXN;i++)
tree->next[i]=NULL;
return tree;
}
/** Adds a word into the data structure. */
void wordDictionaryAddWord(WordDictionary* obj, char* word) {
int i=0,k;
while(word[i]){
k=word[i]-'a';
if(!obj->next[k]){
WordDictionary* temp=wordDictionaryCreate();
obj->next[k]=temp;
}
obj=obj->next[k];
i++;
}
obj->end=true;
}
//递归回溯
//主要思路:
//若index没有到strlen(word), 两种情况:
//1.word[index]=='.':递归回溯,一个一个试,若存在一个成了,返回true,否则返回false;
//2.word[index]!='.':直接比较下一个;
//注意点:比较的是obj->next[]里有没有word[index],当index==strlen(word)-1时,虽然是比较的最后一位,但是,此时obj还在树中倒数第二位位置。
//当index=strlen(word)时,此时虽然index已经超了,但是obj指的是字典树中该单词的最后一位,这时才知道有没有end;
//当然,若只是判断前缀的话,index==strlen(word)-1时已经可以返回了。
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool find(WordDictionary* obj, char* word,int index){
if(obj){
if(index==strlen(word))
return obj->end;
if(word[index]=='.'){
for(int i=0;i<MAXN;i++)
if(find(obj->next[i],word,index+1))
return true;
return false;
}
return find(obj->next[word[index]-'a'],word,index+1);
}
return false;
}
bool wordDictionarySearch(WordDictionary* obj, char* word) {
return find(obj,word,0);
}
void wordDictionaryFree(WordDictionary* obj) {
if(!obj)
return;
for(int i=0;i<MAXN;i++){
if(obj->next[i])
wordDictionaryFree(obj->next[i]);
}
free(obj);
}
/**
* Your WordDictionary struct will be instantiated and called as such:
* struct WordDictionary* obj = wordDictionaryCreate();
* wordDictionaryAddWord(obj, word);
* bool param_2 = wordDictionarySearch(obj, word);
* wordDictionaryFree(obj);
*/
3.知识点:
字典树+递归回溯;