题目:
题解:
cpp
typedef struct WordDictionary_tag{
struct WordDictionary_tag *next[26];
bool finish;
} WordDictionary;
/** Initialize your data structure here. */
WordDictionary* wordDictionaryCreate() {
WordDictionary *wd = (WordDictionary*) malloc(sizeof(WordDictionary));
memset(wd->next, 0, sizeof(wd->next));
wd->finish = false;
return wd;
}
void wordDictionaryAddWord(WordDictionary* obj, char * word) {
for (int i = 0; word[i]; i++){
if (obj->next[word[i] - 'a']){
obj = obj->next[word[i] - 'a'];
continue;
}
obj->next[word[i] - 'a'] = (WordDictionary*) malloc(sizeof(WordDictionary));
obj = obj->next[word[i] - 'a'];
memset(obj->next, 0, sizeof(obj->next));
obj->finish = false;
}
obj->finish = true;
}
bool wordDictionarySearch(WordDictionary* obj, char * word) {
if (!obj){
return false;
}
if (!word[0]){
return obj->finish;
}
if (word[0] != '.'){
return wordDictionarySearch(obj->next[word[0] - 'a'], word + 1);
}
for (int i = 0; i < 26; i++){
if (wordDictionarySearch(obj->next[i], word + 1)){
return true;
}
}
return false;
}
void wordDictionaryFree(WordDictionary* obj) {
for (int i = 0; i < 26; i++){
if (obj->next[i]){
wordDictionaryFree(obj->next[i]);
}
}
free(obj);
}