poj_3461 Oulipo(KMP:找出所有模式串)

本題就是經典的模式串匹配問題,只需要對上文中的程序稍作修改即可。(hihoCoder上的KMP算法一題,與本題一模一樣)

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

void getNext(char t[], int next[])
{
    int i=0, j=-1, tLen=strlen(t);
    next[i]=j;

    while (i<tLen)
        if (j==-1 || t[i]==t[j])
        {
            i++;j++;
            if (t[i]!=t[j]) next[i]=j; else next[i]=next[j];
        }
        else j=next[j];
}

int kmpMain(char s[], char t[], int next[], int pos)
{
    int i=pos, j=0, sLen=strlen(s), tLen=strlen(t),total=0;

    while (i<sLen)
    {
        if (j==-1 || s[i]==t[j]){i++; j++;}
        else j=next[j];
        if (j==tLen) {total++; j=next[j];} //修改的地方
    }

    return total;
}

int main()
{
    char w[10001],t[1000001];
    int n,i,next[10001];
    scanf("%d",&n);
    for (i=0;i<n;i++)
    {
        scanf("%s",w);
        scanf("%s",t);
        getNext(w,next);
        printf("%d\n",kmpMain(t,w,next,0));
    }
    return 0;
}


發佈了44 篇原創文章 · 獲贊 9 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章