Skip to content

Commit 2ce956b

Browse files
committed
Add Z-algorithm
1 parent 5f8725d commit 2ce956b

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

z_algorithm.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include <bits/stdc++.h>
2+
#define ll long long
3+
using namespace std;
4+
5+
vector<ll> z_function(const string& s) {
6+
ll n = s.length();
7+
vector<ll> z(n);
8+
9+
for (ll i = 1, l = 0, r = 0; i < n; i++) {
10+
if (i <= r) {
11+
z[i] = min(z[i-l], r-i+1);
12+
}
13+
while (i + z[i] < n and s[z[i]] == s[i+z[i]]) {
14+
++z[i];
15+
}
16+
if (i + z[i] - 1 > r) {
17+
l = i, r = i + z[i] - 1;
18+
}
19+
}
20+
return z;
21+
}
22+
23+
int main() {
24+
string s("aabaaba");
25+
auto z = z_function(s);
26+
27+
cout << s << endl;
28+
for (auto val : z) {
29+
cout << val << " ";
30+
}
31+
return 0;
32+
}

0 commit comments

Comments
 (0)