-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZ-function.cpp
More file actions
47 lines (47 loc) · 784 Bytes
/
Z-function.cpp
File metadata and controls
47 lines (47 loc) · 784 Bytes
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
void check_pattern() {
string a, b;
cin >> a >> b;
string s = b + "$" + a;
int n = (int)s.size();
int b_size = (int)b.size();
vector<int> ans;
vector<int> Z(n);
int L = 0, R = 0;
for (int i = 1; i < n; ++i) {
if (i > R) {
L = R = i;
while (R < n && s[R] == s[R - L]) {
R++;
}
Z[i] = R - L;
R--;
}else {
int k = i - L;
if (Z[k] < R - i + 1) {
Z[i] = Z[k];
}else {
L = i;
while (R < n && s[R] == s[R - L]) {
R++;
}
Z[i] = R - L;
R--;
}
}
}
for (int i = 0; i < n; ++i) {
if (Z[i] == b_size) {
ans.push_back(i - b_size);
}
}
int k = (int)ans.size();
if (k > 0) {
cout << k << "\n";
for (int i = 0; i < k; ++i) {
cout << ans[i] << " ";
}
}else {
cout << "Not Found";
}
cout << "\n\n";
}