-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDesign Add and Search Words Data Structure.cpp
59 lines (51 loc) · 1.48 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
54
55
56
57
58
59
class TrieNode {
public:
char c;
vector<TrieNode*> child;
bool isTerminal;
// Default constructor
TrieNode() {
child.resize(26, nullptr); // Initialize with 26 null pointers
isTerminal = false;
}
// Parameterized constructor
TrieNode(char c) {
this->c = c;
child.resize(26, nullptr); // Initialize with 26 null pointers
isTerminal = false;
}
};
class WordDictionary {
TrieNode* root;
public:
WordDictionary() {
root = new TrieNode();
}
void add(TrieNode* root, string& word, int i) {
if (i >= word.length()) {
root->isTerminal = true;
return;
}
if (root->child[word[i] - 'a'] != nullptr) {
add(root->child[word[i] - 'a'], word, i + 1);
} else {
root->child[word[i] - 'a'] = new TrieNode(word[i]);
add(root->child[word[i] - 'a'], word, i + 1);
}
}
void addWord(string word) {
add(root, word, 0);
}
bool srch(TrieNode* root, string& word, int i) {
if (i >= word.size()) return root->isTerminal;
if (word[i] == '.') {
for (int j = 0; j < 26; j++) {
if (root->child[j] && srch(root->child[j], word, i + 1)) return true;
}
} else if (root->child[word[i] - 'a']) return srch(root->child[word[i] - 'a'], word, i + 1);
return false;
}
bool search(string word) {
return srch(root, word, 0);
}
};