Skip to content

Commit 8be81ef

Browse files
committed
Z-Algorithm - bugfix - found in CC CookOff May20
1 parent 4bf5876 commit 8be81ef

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

Library/Miscellanious/z-algo.cpp

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
//Z-Algorithm
22
//z[i] is length of prefix starting from i
3-
int z[N];
4-
void go(string s){
3+
4+
// always pass stirng by reference, weird how it got me SIGSEGV in a Codechef problem
5+
// https://codeforces.com/blog/entry/77906
6+
vector<int> go(const string &s){
7+
vector<int> z(s.size(), 0);
58
int i, n = s.size(), L = 0, R = 0;
69
z[0] = 0;
710
Fo(i, 1, n){
@@ -22,5 +25,31 @@ void go(string s){
2225
}
2326
}
2427
}
25-
28+
29+
return z;
2630
}
31+
32+
33+
// another implementation
34+
template <typename T>
35+
vector<int> z_function(int n, const T &s) {
36+
vector<int> z(n, n);
37+
int l = 0, r = 0;
38+
for (int i = 1; i < n; i++) {
39+
z[i] = (i > r ? 0 : min(r - i + 1, z[i - l]));
40+
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {
41+
z[i]++;
42+
}
43+
if (i + z[i] - 1 > r) {
44+
l = i;
45+
r = i + z[i] - 1;
46+
}
47+
}
48+
return z;
49+
}
50+
51+
template <typename T>
52+
vector<int> z_function(const T &s) {
53+
return z_function((int) s.size(), s);
54+
}
55+

0 commit comments

Comments
 (0)