「AcWing学习记录」KMP

AcWing 831. KMP字符串

原题链接

1.暴力算法怎么做

char s[N], p[M];
for(int i = 1; i + m - 1 <= n; i++)
{
    bool flag = true;
    for(int j = 1; j <= m; j++)
        if(s[i + j - 1] != p[j])
        {
            flag = false;
            break;
        }
}

2.如何去优化
时间复杂度\(O(n)\)
image

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1e5 + 10, M = 1e6 + 10;

int n, m;
char s[M], p[N];
int ne[N];

int main()
{
    cin >> n >> p + 1 >> m >> s + 1;

    for(int i = 2, j = 0; i <= n; i++)
    {
        while(j && p[i] != p[j + 1]) j = ne[j];
        if(p[i] == p[j + 1]) j++;
        ne[i] = j;
    }

    for(int i = 1, j = 0; i <= m; i++)
    {
        while(j && s[i] != p[j + 1]) j = ne[j];
        if(s[i] == p[j + 1]) j++;
        if(j == n)
        {
            printf("%d ", i - n);
            j = ne[j];
        }
    }

    return 0;
}
posted @ 2023-02-24 23:03  恺雯  阅读(13)  评论(0编辑  收藏  举报