多处用strlen()报TLE😣

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char s1[1000010], s2[1000010];
    scanf("%s", s1);
    scanf("%s", s2);
    int len1 = strlen(s1);
    int len2 = strlen(s2);
    int len = len2;
    int *next = (int *)malloc(sizeof(int) * len2);
    next[0] = 0;
    int x = 1, now = 0;
    while (x < len2)
    {
        if (s2[now] == s2[x])
            next[x++] = ++now;
        else if (now)
            now = next[now - 1];
        else
            next[x++] = 0;
    }
    x = now = 0;
    while (x < len1)
    {
        if (s1[x] == s2[now])
        {
            x++;
            now++;
        }
        else if (now)
            now = next[now - 1];
        else
            x++;
        if (now == len2)
        {
            printf("%d\n", x - now + 1);
            now = next[now - 1];
        }
    }
    while (len2--)
    {
        printf("%d ", next[len - len2 - 1]);
    }
    return 0;
}

P3375 【模板】KMP字符串匹配

此文章已被阅读次数:正在加载...更新于