Skip to content

Commit a705e6f

Browse files
committed
Design Add And Search Words Data Structure solution
1 parent 8edebd3 commit a705e6f

File tree

1 file changed

+60
-0
lines changed
  • design-add-and-search-words-data-structure

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Trie{
2+
public:
3+
Trie* children[26];
4+
bool isEnd;
5+
6+
Trie(){
7+
for(int i = 0; i < 26; i++)
8+
children[i] = nullptr;
9+
10+
isEnd = false;
11+
}
12+
};
13+
14+
class WordDictionary {
15+
private:
16+
Trie* trie;
17+
public:
18+
WordDictionary() {
19+
trie = new Trie();
20+
}
21+
22+
void addWord(string word) {
23+
Trie* node = trie;
24+
25+
for(char ch : word){
26+
int index = ch - 'a';
27+
28+
if(node->children[index] == nullptr)
29+
node->children[index] = new Trie();
30+
31+
node = node->children[index];
32+
}
33+
34+
node->isEnd = true;
35+
}
36+
37+
bool dfs(Trie* node, int index, string word){
38+
if(node == nullptr)
39+
return false;
40+
41+
if(index == word.length())
42+
return node->isEnd;
43+
44+
char ch = word[index];
45+
46+
if(ch == '.'){
47+
for(int i = 0; i < 26; i++){
48+
if(dfs(node->children[i], index + 1, word) == true)
49+
return true;
50+
}
51+
}else
52+
return dfs(node->children[ch-'a'], index + 1, word);
53+
54+
return false;
55+
}
56+
57+
bool search(string word) {
58+
return dfs(trie, 0, word);
59+
}
60+
};

0 commit comments

Comments
 (0)