3.Design Add and Search Words Data Structure
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)
Addsword
to the data structure, it can be matched later.bool search(word)
Returnstrue
if there is any string in the data structure that matchesword
orfalse
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 True
Solution: (Trie)
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;
}
};
Last updated
Was this helpful?