HDU1686 - Oulipo

求模式串在待匹配串的出现次数。

Input

第一行是一个数字T,表明测试数据组数。
之后每组数据都有两行:第一行为模式串,长度不大于10000;第二行为待匹配串,长度不大于1000000。所有字符串只由大写字母组成。

Output

每组数据输出一行结果。

Sample Input

4
ABCD
ABCD
ABA
ABABABA
CDCDCDC
CDC
KMP
NAIVE

Sample Output

1
3
0
0
#include <iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=1000010;
char str[maxn],pat[maxn];//pat为模式串,str为主串
int Next[maxn]; //Next[x]下标x表示匹配失败处字符下标
//模式串pat的前缀与x位置的后缀的最大匹配字符个数-1
void GetNext(char *pat)
{
    int LenPat = strlen(pat);
    int i = 0,j = -1;
    Next[0] = -1;
    while(i < LenPat)
    {
        if(j == -1 || pat[i] == pat[j])
        {
            i++,j++;
            Next[i] = j;
        }
        else
            j = Next[j];
    }
}

int KMP()//返回模式串pat在str中第一次出现的位置
{
    int LenStr = strlen(str);
    int LenPat = strlen(pat);
    GetNext(pat);
    int i = 0,j = 0;
    int ans = 0;//计算模式串在主串匹配次数
    while(i < LenStr)
    {
        if(j == -1 || str[i] == pat[j])
            i++,j++;
        else
            j = Next[j];
        if(j == LenPat)
        {
            ans++;// ans存放匹配次数,去掉return,最后返回ans
            //return i - LenPat + 1;
        }
    }
    //return -1;//没找到匹配位置
    return ans;//返回匹配次数。
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s%s",pat,str);
        int i=KMP();
        printf("%d\n",i);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41785863/article/details/81570957
今日推荐