Prefix function
At index , look only at the prefix of ending at . Then is the length of its longest suffix that is also a prefix. The whole substring doesn’t count.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
a |
b |
a |
c |
a |
b |
a |
|
| 0 | 0 | 1 | 0 | 1 | 2 | 3 |
At , look at abaca. It starts and ends with a, and nothing longer matches both ends except abaca itself, so .
Implementation
vector<int> prefix_function(string const& S) {
int N = S.size();
vector<int> pi(N);
for (int i = 1; i < N; i++) {
int j = pi[i-1];
while (j > 0 && S[i] != S[j]) j = pi[j-1];
if (S[i] == S[j]) j++;
pi[i] = j;
}
return pi;
}
Interface
| Operation | Description | Time |
|---|---|---|
prefix_function(S) |
Returns the array for the string S of length . |