Skip to main content

Knuth–Morris–Pratt algorithm

Algorithm::prefix_function | String::prefix_function
namespace Algorithm {
template<typename T>
std::vector<int32_t> prefix_function(std::span<T> const& s) {
int32_t n = static_cast<int32_t>(s.size());
std::vector<int32_t> p(n); p[0] = 0;
for (int i = 1; i < n; ++i) {
int32_t j = p[i - 1];
while (j > 0 && s[j] != s[i]) j = p[j - 1];
p[i] = (s[i] == s[j]) ? j + 1 : j;
}
return p;
}
}

namespace String {
std::vector<int> prefix_function(std::string const& s) {
return Algorithm::prefix_function<char const>({s.begin(), s.length()});
}
}

Theory

  • In the context of KMP algorithm, the function String::prefix_function is also called failure function.