-
Notifications
You must be signed in to change notification settings - Fork 0
/
Design Add And Search Words Data Structure.cpp
53 lines (48 loc) · 1.42 KB
/
Design Add And Search Words Data Structure.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
class WordDictionary {
public:
WordDictionary *children[26] = {nullptr};
bool ok = false;
WordDictionary() {}
~WordDictionary() {
for (int i = 0; i < 26; ++i) {
if (children[i] != nullptr) {
delete children[i];
}
}
}
void addWord(std::string word) {
WordDictionary *cur = this;
std::cout << std::endl;
for (char c : word) {
std::cout << c << std::endl;
if (!cur->children[c - 'a']) {
cur->children[c - 'a'] = new WordDictionary;
}
cur = cur->children[c - 'a'];
}
std::cout << "set ok" << std::endl;
cur->ok = true;
}
bool search(std::string word) { return searchHelper(word, 0); }
bool searchHelper(const std::string &word, int start) {
if (start == word.size() - 1) {
return ok;
}
if (word[start] == '.') {
bool found = false;
for (int i = 0; i < 26; ++i) {
if (children[i] && children[i]->searchHelper(word, start + 1)) {
found = true;
break;
}
}
return found;
} else {
if (!children[word[start] - 'a']) {
return false;
}
return children[word[start] - 'a']->searchHelper(word, start + 1);
}
}
};