Skip to content

Commit cd68206

Browse files
committed
z algorithm
1 parent 39d2ddd commit cd68206

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Z-Algorithm/z.cpp

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
// z_function is the number of characters ahead that is also the prefix starting from index i
5+
vector<int> z_function(string s) {
6+
int n = s.length();
7+
vector<int> z(n);
8+
for (int i = 1, l = 0, r = 0; i < n; ++i) {
9+
if (i <= r)
10+
z[i] = min (r - i + 1, z[i - l]);
11+
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
12+
++z[i];
13+
if (i + z[i] - 1 > r)
14+
l = i, r = i + z[i] - 1;
15+
}
16+
return z;
17+
}
18+
19+
int main(){
20+
string s;
21+
cin >> s;
22+
for(auto z : z_function(s)) cout << z << " ";
23+
}

0 commit comments

Comments
 (0)