KMP-返回匹配次数

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;

#define LL long long
#define maxn 10010
#define mod 100000007

char a[maxn * 100], b[maxn];
int Next[maxn], n, m;

void Get_Next(char b[], int m)
{
    int i, j;
    j = Next[0] = -1;
    i = 0;

    while (i < m)
    {
        while (j != -1 && b[i] != b[j])
            j = Next[j];

        Next[++i] = ++j;
    }
}

int kmp(char a[], char b[])
{
    int ans, i, j;
    i = j = ans = 0;
    Get_Next(b, m);
    while (i < n)
    {
        while (j != -1 && a[i] != b[j])
            j = Next[j];
        j++, i++;
        if (j == m)
        {
            ans++;
            j = Next[j];///匹配成功后,当做失配,移动j到Next处
        }
    }
    return ans;
}

int main()
{
    int T;
    scanf("%d", &T);

    while (T--)
    {
        scanf("%s %s", b, a);
        n = strlen(a);
        m = strlen(b);
        printf("%d\n", kmp(a, b));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_31741481/article/details/83548584
今日推荐