Skip to content

Commit 2f63329

Browse files
committed
z algorithm
1 parent 53e8df9 commit 2f63329

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

z.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Z-algorithm
2+
// https://snuke.hatenablog.com/entry/2014/12/03/214243
3+
// https://youtu.be/Uqtxz1KTKOQ?t=9214
4+
struct Z {
5+
int n;
6+
string s;
7+
vector<int> z;
8+
Z() {}
9+
Z(const string& s): s(s) { init();}
10+
void init() {
11+
n = s.size();
12+
z = vector<int>(n);
13+
z[0] = n;
14+
for (int i = 1, j = 0; i < n;) {
15+
while (i+j < n && s[i+j] == s[j]) ++j;
16+
z[i] = j;
17+
if (j) {
18+
int k = 1;
19+
while (i+k < n && k+z[k] < j) {
20+
z[i+k] = z[k];
21+
k++;
22+
}
23+
i += k; j -= k;
24+
} else i++;
25+
}
26+
}
27+
int operator[](int i) const { return z[i];}
28+
};

0 commit comments

Comments
 (0)