-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path1032. Stream of Characters.cpp
58 lines (56 loc) · 1.48 KB
/
1032. Stream of Characters.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
class StreamChecker {
class Node {
public:
bool isEnd;
Node* chars[26];
Node() {
isEnd = false;
for (int i=0; i<26; ++i) {
chars[i] = nullptr;
}
}
};
Node*root;
queue<Node*>q;
void insert(const string &s) {
Node*temp = root;
for (auto&chr:s) {
int x = int(chr - 'a');
if (temp -> chars[x] == nullptr) {
temp -> chars[x] = new Node();
}
temp = temp -> chars[x];
}
temp -> isEnd = true;
}
public:
StreamChecker(vector<string>& words) {
root = new Node();
for (auto&word: words) {
insert(word);
}
}
bool query(char letter) {
int idx = int(letter -'a');
Node*temp = root;
q.push(temp);
const int&n = q.size();
bool isEnd = false;
for (int i=0; i<n; ++i) {
Node*current = q.front(); q.pop();
if (current -> chars[idx] != nullptr) {
current = current-> chars[idx];
if (current->isEnd) {
isEnd = true;
}
q.push(current);
}
}
return isEnd;
}
};
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker* obj = new StreamChecker(words);
* bool param_1 = obj->query(letter);
*/