-
Notifications
You must be signed in to change notification settings - Fork 0
/
Z_Function.cpp
47 lines (40 loc) · 875 Bytes
/
Z_Function.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
#include <bits/stdc++.h>
using namespace std;
// Longest prefix start at index i that match with string s, O(n)
vector<int> z_function(const string &s) {
int n = s.size();
vector<int> z(n);
int l = 0, r = 0;
for (int i = 1; i < n; i++) {
if (i < r) {
z[i] = min(r - i, z[i - l]);
}
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {
z[i]++;
}
if (i + z[i] > r) {
l = i;
r = i + z[i];
}
}
return z;
}
void solve() {
string s;
cin >> s;
int n = s.size();
vector<int> z = z_function(s);
for (int i = 0; i < n; i++) {
cout << z[i] << " \n"[i == n - 1];
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}