211. Add and Search Word - Data structure design (Medium)
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
.
Solution:
struct TrieNode {
bool isWord;
vector<TrieNode*> children;
TrieNode(): isWord(false), children(26, NULL) {}
};
class WordDictionary {
bool helper(TrieNode* p, string& word, int idx) {
if (idx == word.size()) return p->isWord;
if (word[idx] == '.') {
for (auto& a: p->children) {
if (a && helper(a, word, idx+1)) return true;
}
} else {
int pos = word[idx]-'a';
if (p->children[pos]) return helper(p->children[pos], word, idx+1);
}
return false;
}
public:
/** Initialize your data structure here. */
WordDictionary() {
root = new TrieNode();
}
/** Adds a word into the data structure. */
void addWord(string word) {
TrieNode* cur = root;
for (char c: word) {
int pos = c-'a';
if (!cur->children[pos]) cur->children[pos] = new TrieNode();
cur = cur->children[pos];
}
cur->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(root, word, 0);
}
private:
TrieNode* root;
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* bool param_2 = obj.search(word);
*/