KMP

· · 个人记录

前缀函数

约定字符串下标从 0 开始。

求字符串 s 的每个前缀 s[0 \dots i] 的最长公共真前后缀的长度 \pi[i](真前缀,即长度小于字符串长度的前缀,真后缀同理)。

考虑如何利用已经求出的 \pi[0 \dots i - 1] 求出 \pi[i]。考察下面的例子:

\textcolor{green}{\texttt{abab}} \underset{\pi[i-1]}{\textcolor{red}{\texttt{c}}} \textcolor{green}{\texttt{abab}} \underset{i}{\textcolor{blue}{\texttt{a}}}

现在我们试图让 \textcolor{blue}{\texttt{a}} 接上已经匹配成功的 \textcolor{green}{\texttt{abab}},让 s_i 与 s_j 匹配,其中 j = \pi[i-1]。但是失配。

\textcolor{green}{\texttt{ab}} \underset{\pi[j-1]}{\textcolor{blue}{\texttt{a}}} \texttt{bc} \texttt{ab}\textcolor{green}{\texttt{ab}} \underset{i}{\textcolor{blue}{\texttt{a}}}

退而求其次,我们让待匹配下标往前跳,变为 \pi[j-1],匹配成功,\pi[i] = \pi[j-1] + 1(由于字符串下标从 0 开始,而 \pi 记录长度,所以要 +1)。

一般地,设 j = \pi[i-1],重复以下操作直至结束:

代码如下:

border[0] = 0;
for (int i = 1; i < (int)s.size(); i ++) {
    int j = border[i - 1];
    while (1) {
        if (s[j] == s[i]) {
            border[i] = j + 1; break;
        } else {
            if (!j) break;
            else j = border[j - 1];
        }
    }
    if (border[i] == (int)s2.size()) {
        cout << i - 2 * (int)s2.size() + 1 << endl;
    }
}

P3375 【模板】KMP

给定文本串 t 和模式串 s,查找 s 在 t 中的所有出现。

构造字符串 p = s + \# + t,其中 \# 为不在 s,t 的字符集中的特殊字符。

求出 p 的前缀函数,若 \pi[i] = len(s),则 p[i - len(s) + 1 \dots i] 与 s 匹配,对应到 t 上即可。

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
const int N = 1e6 + 5;

int border[N << 1];

signed main() {
    //freopen("", "r", stdin);
    //freopen("", "w", stdout);
    ios::sync_with_stdio(0), cin.tie(0);
    string s1, s2; cin >> s1 >> s2;
    string s = s2 + '#' + s1;
    border[0] = 0;
    for (int i = 1; i < (int)s.size(); i ++) {
        int j = border[i - 1];
        while (1) {
            if (s[j] == s[i]) {
                border[i] = j + 1; break;
            } else {
                if (!j) break;
                else j = border[j - 1];
            }
        }
        if (border[i] == (int)s2.size()) {
            cout << i - 2 * (int)s2.size() + 1 << endl;
        }
    }
    for (int i = 0; i < (int)s2.size(); i ++) cout << border[i] << ' ';
    cout << endl;
    return 0;
}