题目描述:
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.
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 WordDictionary {
public:
struct TrieNode{
public:
char c;
TrieNode* v[26];
bool isWord = false;
TrieNode(): c('#') {
for(int i = 0; i < 26; i++) v[i] = NULL;
}
};
/** Initialize your data structure here. */
WordDictionary() {
root = new TrieNode();
}
/** Adds a word into the data structure. */
void addWord(string word) {
TrieNode* p = root;
for(int i = 0; i < word.size(); i++)
{
int j = word[i] - 'a';
if (p->v[j] == NULL) p->v[j] = new TrieNode();
p = p->v[j];
}
p->isWord = 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 helper(word, root, 0);
}
bool helper(string word, TrieNode* p, int i)
{
if(i == word.size()) return p->isWord;
if(word[i] != '.')
{
int j = word[i] - 'a';
if(p->v[j] == NULL) return false;
else return helper(word, p->v[j], i + 1);
}
else
{
bool isWord = false;
for(int j = 0; j < 26; j++)
if(p->v[j] != NULL && helper(word, p->v[j], i + 1)) isWord = true;;
return isWord;
}
}
private:
TrieNode* root;
};