The Z Algorithm is an algorithm that computes for a string of length , where
in time and space.
Tip
This problem can also be solved by Kasai’s Algorithm in time and space.
Algorithm 0
Applying the definition to find yields an algorithm that solves the problem in time and space.
std::vector<int> z(int n, const std::string &s) {
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 to find a lower bound for yield an algorithm that solves the problem in time and space.
std::vector<int> z(int n, const std::string &s) {
std::vector<int> z(n);
z[0] = n;
for (int i = 1, j = -1; i < n; i++) {
z[i] = ~j && i < j + z[j] ? std::min(z[i - j], j + z[j] - i) : 0;
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {
z[i]++;
}
if (j == -1 || j + z[j] < i + z[i]) {
j = i;
}
}
return z;
}Proof
It is easy to prove that the total number of executions of
z[i]++is bounded by