-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
70 lines (59 loc) · 1.76 KB
/
main.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
#include <bits/stdc++.h>
using namespace std;
struct Node {
unordered_map<int, int> count;
Node* next[26] = {};
};
vector<int> solution(vector<string> words, vector<string> queries) {
Node* g = new Node();
Node* r_g = new Node();
for (const string& word : words) {
Node* node = g;
Node* r_node = r_g;
int sz = word.size();
g->count[sz]++;
r_g->count[sz]++;
for (int i = 0; i < sz; i++) {
int value = word[i] - 'a';
int r_value = word[sz - i - 1] - 'a';
if (!node->next[value]) {
node->next[value] = new Node();
}
if (!r_node->next[r_value]) {
r_node->next[r_value] = new Node();
}
node = node->next[value];
node->count[sz]++;
r_node = r_node->next[r_value];
r_node->count[sz]++;
}
}
vector<int> ans;
for (const string& q : queries) {
int sz = q.size();
int result = 0;
if (q.front() == '?' && q.back() == '?') {
result = g->count[sz];
} else if (q.front() == '?') {
Node* node = r_g;
for (int i = sz - 1; i >= 0 && node; i--) {
if (q[i] == '?') {
result = node->count[sz];
break;
}
node = node->next[q[i] - 'a'];
}
} else if (q.back() == '?') {
Node* node = g;
for (int i = 0; i < sz && node; i++) {
if (q[i] == '?') {
result = node->count[sz];
break;
}
node = node->next[q[i] - 'a'];
}
}
ans.push_back(result);
}
return ans;
}