You should design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary() Initializes the object.
void addWord(word) adds word to the data structure, it can be matched later.
bool search(word) returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.
Example:
Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]
Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return Tru
代码:
typedef struct WordDictionary {
struct WordDictionary *next[26];
// bool isWord;
} WordDictionary;
/** Initialize your data structure here. */
WordDictionary* wordDictionaryCreate() {
WordDictionary *pDict = (WordDictionary *)malloc(sizeof(WordDictionary));
// pDict->isWord = false;
int i;
for(i = 0; i < 26; ++i)
{
pDict->next[i] = NULL;
}
return pDict;
}
/** Adds a word into the data structure. */
void wordDictionaryAddWord(WordDictionary* obj, char * word) {
while( *word != '\0')
{
int idx = *word - 'a';
if(obj->next[idx] == NULL)
{
obj->next[idx] = (WordDictionary *)malloc(sizeof(WordDictionary));
int j;
for(j = 0; j < 26; ++j)
{
obj->next[idx]->next[j] = NULL;
}
// obj->next[idx]->isWord = false;
}
++word;
// if(*word == '\0')
// {
// obj->next[idx]->isWord = true;
// }
obj = obj->next[idx];
}
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool wordDictionarySearch(WordDictionary* obj, char * word) {
while( *word != '\0')
{
if(*word == '.')
{
int i;
for(i = 0; i < 26; ++i)
{
if(obj->next[i])
{
bool bRet = wordDictionarySearch(obj->next[i], ++word);
if(bRet == true)
{
return true;
}
}
}
return false;
}
else
{
int idx = *word - 'a';
if(obj->next[idx] == false)
{
return false;
}
++word;
obj = obj->next[idx];
}
}
return true;
}
void wordDictionaryFree(WordDictionary* obj) {
int i;
for(i = 0; i < 26; ++i)
{
WordDictionary * pDict = obj->next[i];
if(pDict)
{
wordDictionaryFree(pDict);
}
}
free(obj);
}
/**
* Your WordDictionary struct will be instantiated and called as such:
* WordDictionary* obj = wordDictionaryCreate();
* wordDictionaryAddWord(obj, word);
* bool param_2 = wordDictionarySearch(obj, word);
* wordDictionaryFree(obj);
*/
上面的代码有点问题:
wordDictionarySearch里的
bool bRet = wordDictionarySearch(obj->next[i], ++word);
要改为:
bool bRet = wordDictionarySearch(obj->next[i], word +1);
否则会有内存问题.