forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path(LEETCODE)DesignAddAndSearchWordsDS.cpp
46 lines (42 loc) · 1.41 KB
/
(LEETCODE)DesignAddAndSearchWordsDS.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
class WordDictionary {
vector<WordDictionary*> children;
bool isEndOfWord;
public:
/** Initialize your data structure here. */
WordDictionary(): isEndOfWord(false) {
children=vector<WordDictionary*>(26,nullptr);
}
/** Adds a word into the data structure. */
void addWord(string word) {
WordDictionary *curr = this;
for(char c:word){
if(curr->children[c-'a'] == nullptr){
curr->children[c-'a'] = new WordDictionary();
}
curr = curr->children[c-'a'];
}
curr->isEndOfWord =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) {
WordDictionary *curr = this;
for(int i=0;i<word.length();++i){
char c= word[i];
if(c=='.'){
for(auto ch:curr->children){
if(ch && ch->search(word.substr(i+1))) return true;
}
return false;
}
if(curr->children[c-'a']==nullptr) return false;
curr=curr->children[c-'a'];
}
return curr && curr->isEndOfWord;
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/