-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddAndSearchWordDataStructureDesign.cpp
62 lines (57 loc) · 1.79 KB
/
AddAndSearchWordDataStructureDesign.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
60
61
62
class TrieNode{
public:
bool isEnd;
char val;
unordered_map<char,TrieNode *> children;
TrieNode(char val): isEnd{false}, val{val} {
}
};
class WordDictionary {
public:
/** Initialize your data structure here. */
TrieNode * root;
WordDictionary() {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
root = new TrieNode('$');
}
/** Adds a word into the data structure. */
void addWord(string word) {
TrieNode * curr = root;
for(int i = 0; i<word.size(); i++){
if(curr->children.find(word[i]) == curr->children.end()){
curr->children[word[i]] = new TrieNode(word[i]);
}
curr = curr->children[word[i]];
}
curr->isEnd = 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) {
// cout<<"searching "<<word<<endl;
TrieNode * curr = root;
for(int i = 0; i<word.size(); i++){
if(word[i] == '.'){
//explore all the children looking for the string
for(auto x: curr->children){
string temp = word;
temp[i] = x.first;
if(search(temp)){
return true;
}
}
}
if(curr->children.find(word[i]) == curr->children.end()){
return false;
}
curr = curr->children[word[i]];
}
return curr->isEnd;
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/