Design a data structure that supports adding new words and finding if a string matches any previously added string.
Copy 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 True
Copy class WordDictionary
{
public:
/** Initialize your data structure here. */
struct TrieNode
{
char val;
int count;
int endsHere;
TrieNode *child[26];
};
TrieNode *addNode(char val)
{
TrieNode *temp = new TrieNode;
temp->val = val;
temp->endsHere = 0;
temp->count = 0;
for (int i = 0; i < 26; i++)
{
temp->child[i] = NULL;
}
return temp;
}
TrieNode *root;
WordDictionary()
{
root = addNode('/');
}
void addWord(string word)
{
TrieNode *cur = root;
for (int i = 0; i < word.length(); i++)
{
int idx = word[i] - 97;
if (cur->child[idx])
{
cur->child[idx]->count++;
}
else
{
cur->child[idx] = addNode(word[i]);
}
cur = cur->child[idx];
}
cur->endsHere++;
}
bool find(string word, TrieNode *root)
{
TrieNode *cur = root;
for (int i = 0; i < word.length(); i++)
{
if (word[i] != '.')
{
if (cur->child[word[i] - 97])
{
cur = cur->child[word[i] - 97];
}
else
{
return false;
}
}
else
{
for (int j = 0; j < 26; j++)
{
string left = word.substr(i+1, word.length() - i-1);
if (cur->child[j] && find(left, cur->child[j]))
{
return true;
}
}
return false;
}
}
if (cur->endsHere > 0)
{
return true;
}
return false;
}
bool search(string word)
{
if (find(word, root))
{
return true;
}
return false;
}
};