-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem208.cpp
53 lines (46 loc) · 1.43 KB
/
problem208.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
class Trie {
public:
static const int MAX_CHAR = 26;
Trie *child[MAX_CHAR];
bool isLeaf{false};
Trie() {
memset(child, 0, sizeof(child));
}
void insert(string word, int index = 0) {
if(index == word.size())
isLeaf = true;
else {
int cur = word[index] - 'a';
if(!child[cur])
child[cur] = new Trie();
child[cur]->insert(word, index+1);
}
}
bool search(string word, int index = 0) {
if(index == word.size())
return isLeaf;
else{
int cur = word[index] - 'a';
if(!child[cur])
return false;
return child[cur]->search(word, index+1);
}
}
bool startsWith(string prefix, int index = 0) {
if(index == (int)prefix.size())
return true;
else{
int cur = prefix[index] - 'a';
if(!child[cur])
return false;
return child[cur]->startsWith(prefix, index+1);
}
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/