算法.kmp

算法.kmp_第1张图片

#include
using namespace std;
const int N = 10010, M = 100010;
int n, m, ne[N];
char p[N], s[M];
int main()
{
    cin >> n >> p + 1 >> m >> s + 1;
    for (int i = 2, j = 0; i <= n; i++)
    {
        while (p[j + 1] != p[i])j = ne[j];
        if (p[j + 1] == p[i])j++;
        ne[i] = j;
       
    }
    for (int i = 1, j = 0; i <= m; i++)
    {
        while (p[j + 1] != s[i])j = ne[j];
        if (p[j + 1] == p[i])j++;
        ne[i] = j;
        if (n == j)
        {
            cout << i - n;
            j = ne[j];
        }

    }

    return 0;
}

kmp这仨人真聪明

你可能感兴趣的:(算法,c++,java)