Manacher’s Algorithm is an algorithm that computes for a string of length , where
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> manacher(int n, const std::string &s) {
std::vector d(n, 0);
for (int i = 0; i < n; i++) {
while (i - d[i] - 1 >= 0 && i + d[i] + 1 < n && s[i - d[i] - 1] == s[i + d[i] + 1]) {
d[i]++;
}
}
return d;
}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> manacher(int n, const std::string &s) {
std::vector<int> d(n);
for (int i = 0, j = -1; i < n; i++) {
d[i] = ~j && i < j + d[j] ? std::min(d[2 * j - i], j + d[j] - i) : 0;
while (i - d[i] - 1 >= 0 && i + d[i] + 1 < n && s[i - d[i] - 1] == s[i + d[i] + 1]) {
d[i]++;
}
if (j == -1 || j + d[j] < i + d[i]) {
j = i;
}
}
return d;
}Proof
It is easy to prove that the total number of executions of
d[i]++is bounded by