forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
57 lines (51 loc) · 1.25 KB
/
Solution.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
class Trie {
private:
Trie* children[26]{};
bool isEnd = false;
public:
void insert(string& w) {
Trie* node = this;
reverse(w.begin(), w.end());
for (char& c : w) {
int idx = c - 'a';
if (!node->children[idx]) {
node->children[idx] = new Trie();
}
node = node->children[idx];
}
node->isEnd = true;
}
bool search(string& w) {
Trie* node = this;
for (int i = w.size() - 1, j = 0; ~i && j < 201; --i, ++j) {
int idx = w[i] - 'a';
if (!node->children[idx]) {
return false;
}
node = node->children[idx];
if (node->isEnd) {
return true;
}
}
return false;
}
};
class StreamChecker {
public:
Trie* trie = new Trie();
string s;
StreamChecker(vector<string>& words) {
for (auto& w : words) {
trie->insert(w);
}
}
bool query(char letter) {
s += letter;
return trie->search(s);
}
};
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker* obj = new StreamChecker(words);
* bool param_1 = obj->query(letter);
*/