HDU 1618 Oulipo KMP解决问题的方法

鉴于两个字符串,寻找一个字符串的频率,另一个字符串出现。

原版的kmp另一个陷阱。以下凝视了,标不是踩着好,有加班一定几率,也有机会错误,根据不同的字符串可以是详细。

变化看起来像一个,kmp速度是非常快的。


#include <stdio.h>
#include <string.h>
    
const int MAX_TXT = 1000001;
const int MAX_WORD = 10001;
int gWlen, gTlen;
char word[MAX_WORD];
int next[MAX_WORD];
char txt[MAX_TXT];

void getNext()
{
    memset(next, 0, sizeof(int) * gWlen);
    for (int i = 1, j = 0; i < gWlen; )
    {
        if (word[i] == word[j]) next[i++] = ++j;
        else if (j > 0) j = next[j-1];
        else i++;
    }
}

int kmpSearch()
{
    int i = 0, j = 0, ans = 0;
    for (; gWlen-j <= gTlen-i; )
    {
        if (word[j] == txt[i])
        {
            j++; i++;
            if (j == gWlen)
            {
                ans++;
                j = next[j-1];
            }
            //else i++; i++放这里会超时,是一定几率会出现超时。注意了!
        }
        else if (j > 0) j = next[j-1];
        else i++;
    }
    return ans;
}

int main()
{
    int T;
    scanf("%d", &T);
    getchar();
    while (T--)
    {
        gets(word);
        gWlen = strlen(word);
        gets(txt);
        gTlen = strlen(txt);

        getNext();
        printf("%d
", kmpSearch());
    }
    return 0;
}



版权声明:笔者靖心脏,景空间地址:http://blog.csdn.net/kenden23/。只有经过作者同意转载。

原文地址:https://www.cnblogs.com/gcczhongduan/p/4756505.html