Design a data structure that supports the following two operations:
void addWord(word) bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z
or .
. A .
means it can represent any one letter.
For example:
addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z
.
class TrieNode
{
public:
bool isLeaf;
TrieNode *childs[26];
TrieNode()
{
isLeaf = false;
for(int i=0; i<26; i++)
childs[i] = NULL;
}
};
class WordDictionary {
public:
TrieNode *root;
WordDictionary()
{
root = new TrieNode();
}
bool find(string &word, int index, int len, TrieNode *cur)
{
if(index >= len)
return cur->isLeaf;
if(word[index] == '.')
{
for(int i=0; i<26; i++)
{
if(cur->childs[i])
if(find(word, index+1, len, cur->childs[i]))
return true;
}
}
else
{
int ix = word[index] - 'a';
if(!cur->childs[ix])
return false;
return find(word, index+1, len, cur->childs[ix]);
}
return false;
}
// Adds a word into the data structure.
void addWord(string word)
{
int n = word.size();
TrieNode *p = root;
for(int i=0; i<n; i++)
{
int ix = word[i] - 'a';
if(p->childs[ix] == NULL)
{
p->childs[ix] = new TrieNode();
}
p = p->childs[ix];
}
p->isLeaf = true;
}
// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
bool search(string word)
{
return find(word, 0, word.size(), root);
}
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");