-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path1032.cpp
45 lines (39 loc) · 1.05 KB
/
1032.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
class StreamChecker {
class TrieNode {
public:
bool end;
vector<TrieNode *> sub;
TrieNode() : end(false), sub(26, nullptr) {};
};
public:
TrieNode *trie;
string cache;
void Construct(string &word) {
auto root = this->trie;
for (int i = 0; i < word.size(); ++i) {
if (!root->sub[word[i] - 'a'])
root->sub[word[i] - 'a'] = new TrieNode();
root = root->sub[word[i] - 'a'];
}
root->end = true;
}
StreamChecker(vector<string> &words) {
trie = new TrieNode();
for (auto word:words) {
reverse(word.begin(), word.end());
Construct(word);
}
}
bool query(char letter) {
cache += letter;
TrieNode *node = trie;
for (int i = cache.size() - 1; i >= 0; --i) {
if (!node->sub[cache[i] - 'a'])
return false;
node = node->sub[cache[i] - 'a'];
if (node->end)
return true;
}
return false;
}
};