Z function
At each index after zero, compare the string starting at with the start of . Count how many characters match before they differ or you reach the end. By convention, .
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
a |
a |
a |
b |
a |
a |
b |
|
| 0 | 2 | 1 | 0 | 2 | 1 | 0 |
At , compare aab with the start of . The first two characters match, but the third differs, so .
Implementation
vector<int> z_function(string const& S) {
int N = S.size();
vector<int> z(N);
int l = 0, r = 0;
for (int i = 1; i < N; i++) {
if (i < r) z[i] = min(r-i, z[i-l]);
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;
}
Interface
| Operation | Description | Time |
|---|---|---|
z_function(S) |
Returns the array for the string S of length . |