KMP

      A: a b a b a b c

      B: a b a b c

Next:  0 0 1 2 0

暴力:

 1

  A: a b a b a b c

  B: a b a b c

 2

   A: a b a b a b c

   B:    a b a b c

 3 

  A:  a b a b a b c

  B:        a b a b c

KMP

          0 1 2 3 4 5 6

     A: a b a b a b c

     B: a b a b c

Next: 0 0 1 2 0

2.

A[4]

B[2]

A:  a b a b a b c

B:        a b a b c

 


#include <bits/stdc++.h>
using namespace std;

const int maxn = 1e6 + 10;
char str1[maxn], str2[maxn];
int Next[maxn];

void get_Next()
{
    int i, j, m = strlen(str2);
    Next[0] = 0;
    for(i = 1; i < m; i++)
    {
        j = Next[i - 1];
        while(j > 0 && str2[i] != str2[j])
        {
            j = Next[j - 1];
        }
        if(str2[i] == str2[j])
            Next[i] = j + 1;
        else
            Next[i] = 0;
    }
}


int kmp()
{
    int len1 = strlen(str1), len2 = strlen(str2);
    int i, j, ans = 0;
    for(i = 0, j = 0; i < len1; i++)
    {

        while(j > 0 && str1[i] != str2[j])
        {
            j = Next[j - 1];
        }
        if(str1[i] == str2[j])
            j++;
        if(j == len2)
        {
            ans++;
            j = Next[j - 1];//可重复的 比如 AZA
                            //            AZAZAZA 输出3
           // j = 0;                      输出2 不可重复

        }
    }
    return ans;
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%s %s", str2, str1);
        get_Next();
        for(int i=0;i<20;i++){
            printf("%d ",Next[i]);
        }
        int v = kmp();
        printf("%d\n", v);
    }

}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值