Add and Search Word - Data structure design
struct Trie {
bool end;
Trie *next[26];
Trie() {
end = false;
memset(next, 0, sizeof(next));
}
};
class WordDictionary {
Trie *root;
public:
WordDictionary() {
root = new Trie();
}
// Adds a word into the data structure.
void addWord(string word) {
Trie *p = root;
int n = word.length();
for (int i = 0; i < n; ++i) {
int index = int(word[i] - 'a');
if (!p->next[index]) {
p->next[index] = new Trie();
}
p = p->next[index];
}
p->end = 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) {
if (word.empty()) {
return true;
}
return search(root, &word[0]);
}
bool search(Trie *r, const char *s) {
if (!r) {
return false;
}
if (!*s) {
return r->end;
}
if (*s == '.') {
for (int i = 0; i < 26; ++i) {
if (r->next[i] && search(r->next[i], s + 1)) {
return true;
}
}
return false;
} else {
return search(r->next[int(*s - 'a')], s + 1);
}
}
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");