Skip to content

Commit a28ea3f

Browse files
Added solution for add and search word
1 parent 53567c9 commit a28ea3f

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

add_and_search_word.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class WordDictionary {
2+
public:
3+
/** Initialize your data structure here. */
4+
vector<WordDictionary* > children;
5+
bool isEndOfWord;
6+
7+
WordDictionary() {
8+
this->isEndOfWord = false; //determine end of word
9+
this->children = vector<WordDictionary* >(26, nullptr); //for each node, there are 26 possibilities of character in children
10+
}
11+
12+
/** Adds a word into the data structure. */
13+
void addWord(string word) {
14+
auto current_dict = this;
15+
for(auto const c : word) {
16+
if(current_dict->children[c - 'a'] == nullptr) //check if the current char exist in the Trie
17+
current_dict->children[c - 'a'] = new WordDictionary(); //initialize a new dictionary for each possible children
18+
current_dict = current_dict->children[c - 'a']; //increment this pointer
19+
}
20+
current_dict->isEndOfWord = true; //set the flag to true to determine end of word
21+
}
22+
23+
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
24+
bool search(string word) {
25+
26+
auto current_dict = this;
27+
for(int i=0; i<word.length(); i++) {
28+
auto c = word[i];
29+
if(c == '.'){ //iterate through all the possibilities for this edgecase
30+
for(auto ch : current_dict->children)
31+
if(ch && ch->search(word.substr(i+1))) return true;
32+
return false;
33+
}
34+
if(current_dict->children[c - 'a'] == nullptr) return false;
35+
current_dict = current_dict->children[c - 'a']; //increment this pointer
36+
}
37+
return current_dict && current_dict->isEndOfWord;
38+
}
39+
};
40+
41+
/**
42+
* Your WordDictionary object will be instantiated and called as such:
43+
* WordDictionary* obj = new WordDictionary();
44+
* obj->addWord(word);
45+
* bool param_2 = obj->search(word);
46+
*/

0 commit comments

Comments
 (0)