The Z Algorithm is an algorithm that computes for a string of length in time and space, where
Algorithm 0
Applying the definition yields an algorithm that solves the problem in time and space.
std::vector z(n, 0);
for (int i = 0; i < n; i++) {
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {
z[i]++;
}
}
return z;Algorithm 1
Lemma
Proof
Based on Algorithm 0, maintaining and applying the lemma yield an algorithm that solves the problem in time and space.
std::vector<int> z(n);
z[0] = n;
for (int i = 1, l = 0, r = 0; i < n; i++) {
z[i] = i < r ? std::min(z[i - l], r - i) : 0;
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {
z[i]++;
}
if (i + z[i] > r) {
l = i, r = i + z[i];
}
}
return z;Proof
It is easy to prove that the upper bound of the total number of executions of
z[i]++;is