-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC1032.cpp
More file actions
executable file
·66 lines (55 loc) · 1.42 KB
/
LC1032.cpp
File metadata and controls
executable file
·66 lines (55 loc) · 1.42 KB
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
/*
Problem Statement: https://leetcode.com/problems/stream-of-characters/
Space: O(len • words + queries)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
|----------------------|----------------|-------|
| Operations | Time | Space |
|----------------------|----------------|-------|
| StreamChecker(words) | O(len • words) | O(1) |
| add(word) | O(len) | O(1) |
| query(letter) | O(len) | O(1) |
|----------------------|----------------|-------|
*/
class TrieNode {
public:
int words;
vector<TrieNode*> children;
TrieNode() : words(0), children(26) {}
};
class StreamChecker {
private:
int max_len;
deque<char> d;
TrieNode* root;
public:
StreamChecker(vector<string>& words) : max_len(0), root(new TrieNode()) {
for (string& word: words)
add(word);
}
void add(string& word) {
TrieNode* node = root;
int len = word.length();
max_len = max(len, max_len);
for (int i = len - 1; i >= 0; i--) {
int pos = word[i] - 'a';
if (!node->children[pos])
node->children[pos] = new TrieNode();
node = node->children[pos];
}
node->words++;
}
bool query(char letter) {
d.push_front(letter);
TrieNode* node = root;
if (d.size() > max_len)
d.pop_back();
for (char& c: d) {
if (node->words)
break;
else if (!node->children[c - 'a'])
return false;
node = node->children[c - 'a'];
}
return node->words;
}
};