-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
streamChecker.cpp
69 lines (53 loc) · 1.66 KB
/
streamChecker.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
58
59
60
61
62
63
64
65
66
67
68
69
class StreamChecker {
private:
class Trie {
public:
bool is_leaf;
Trie* children[26];
Trie() {
this->is_leaf = false;
for(int i = 0; i < 26; ++i) {
this->children[i] = NULL;
}
}
void insert_reversed(string word) {
reverse(word.begin(), word.end());
Trie* root = this;
for(char c: word) {
int idx = c - 'a';
if(root->children[idx] == NULL)
root->children[idx] = new Trie();
root = root->children[idx];
}
root->is_leaf = true;
}
};
public:
Trie trie;
vector<char> queries;
int longest_word = 0;
StreamChecker(vector<string>& words) {
for(auto& word: words) {
trie.insert_reversed(word);
if(word.size() > longest_word)
longest_word = word.size();
}
}
bool query(char letter) {
queries.insert(queries.begin(), letter);
if(queries.size() > longest_word)
queries.pop_back();
Trie* curr = ≜
for(char c: queries) {
if(curr->is_leaf) return true;
if(curr->children[c - 'a'] == NULL) return false;
curr = curr->children[c - 'a'];
}
return curr->is_leaf;
}
};
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker* obj = new StreamChecker(words);
* bool param_1 = obj->query(letter);
*/