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.
样例
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
注意
You may assume that all words are consist of lowercase letters a-z.
class Node
{
public:
Node *child[26];
bool isEnd;
char val;
Node(char a)
{
val = a;
for (int i = 0; i < 26; i++)
{
child[i] = NULL;
}
isEnd = false;
}
};
class WordDictionary {
public:
WordDictionary()
{
root = new Node(' ');
}
// Adds a word into the data structure.
void addWord(string word) {
// Write your code here
addWordHelp(root, word);
}
// 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) {
// Write your code here
return searchHelp(root, word);
}
private:
void addWordHelp(Node *root, string word)
{
if (root == NULL)
{
return;
}
int n = word.length();
if (n < 1)
{
return;
}
int pos = word[0] - 'a';
if (root->child[pos] == NULL)
{
root->child[pos] = new Node(word[0]);
}
if (n == 1)
{
root->child[pos]->isEnd = true;
}
else
{
addWordHelp(root->child[pos], word.substr(1));
}
}
bool searchHelp(Node *root, string word)
{
if (root == NULL)
{
return false;
}
int n = word.length();
if (n < 1)
{
return true;
}
if (word[0] == '.')
{
for (int i = 0; i < 26; i++)
{
if (root->child[i] != NULL)
{
if (n == 1)
{
if (root->child[i]->isEnd)
{
return true;
}
}
else
{
if (searchHelp(root->child[i], word.substr(1)))
{
return true;
}
}
}
}
return false;
}
else
{
int pos = word[0] - 'a';
if (root->child[pos] != NULL)
{
if (n == 1)
{
if (root->child[pos]->isEnd)
{
return true;
}
else
{
return false;
}
}
else
{
return searchHelp(root->child[pos], word.substr(1));
}
}
else
{
return false;
}
}
}
Node *root;
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");