-
Notifications
You must be signed in to change notification settings - Fork 0
/
1032.stream-of-characters.trie.3.cpp
74 lines (68 loc) · 1.61 KB
/
1032.stream-of-characters.trie.3.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
70
71
72
73
74
/*
* @lc app=leetcode id=1032 lang=cpp
*
* [1032] Stream of Characters
*/
// @lc code=start
auto speedup = [](){
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
return 0;
}();
struct TrieNode {
int begin;
int next[26];
};
TrieNode trie[30000];
class StreamChecker {
int root;
int index;
int maxLength = 0;
char d[2001];
int begin = 0;
int end = 1;
int useNext() {
memset(trie + index, 0 , sizeof(TrieNode));
return index++;
}
public:
StreamChecker(vector<string>& words) {
sort(words.begin(), words.end());
index = 0;
root = useNext();
for(auto &word: words) {
auto cur = &(trie[root]);
for(int i = word.length() - 1; i >= 0; --i) {
char c = word[i] - 'a';
if(!cur->next[c]) {
cur->next[c] = useNext();
}
if(!i) {
cur->begin |= (1 << c);
}
cur = &(trie[cur->next[c]]);
}
if(word.length() > maxLength) maxLength = word.length();
}
}
bool query(char letter) {
d[end] = letter - 'a';
end = end == 2000 ? 0 : end + 1;
if((end - begin + 2000) % 2001 > maxLength) begin += 1;
if(begin == 2000) begin = 1;
auto cur = &(trie[root]);
for(int i = (end + 2000) % 2001; i != begin; i = (i + 2000) % 2001) {
char c = d[i];
if(!cur->next[c]) return false;
else if(cur->begin & (1 << c)) return true;
else cur = &(trie[cur->next[c]]);
}
return false;
}
};
// Accepted
// 17/17 cases passed (136 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 100 % of cpp submissions (90.6 MB)
// @lc code=end