kmp算法代码

#include <iostream>

#define N 100010
#define M 1000010

using namespace std;

int main()
{
    int n, m;
    char P[N], S[M];
    int next[N];
    next[0] = -1;
    
    cin >> n >> P >> m >> S ;
    
    // 计算next数组
    for (int i = 1, j = -1; i < n; i ++ )
    {
        while (j!=-1 && P[i] != P[j + 1])
            j = next[j];
        if (P[i] == P[j + 1])
            j++;
        next[i] = j;
    }
    
    // 匹配
    for (int i = 0, j = -1; i < m; i ++)
    {
        while (j!=-1 && S[i] != P[j + 1])
            j = next[j];
        if (S[i] == P[j + 1])
            j++;
        if (j == n-1)
        {
            cout << i - n + 1 << " ";
            j = next[j];
        }
    }

    // return 0;
}
posted @ 2021-05-10 15:52  _STAyy  阅读(103)  评论(0编辑  收藏  举报