We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 39d2ddd commit cd68206Copy full SHA for cd68206
Z-Algorithm/z.cpp
@@ -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