zcmu-1953 #103. 子串查找(KMP算法,字符串匹配)

Description

这是一道模板题。

给定一个字符串 A 和一个字符串 B,求 B 在 A 中的出现次数。

A 中不同位置出现的 B 可重叠。

Input

输入共两行,分别是字符串 A 和字符串 B。

Output

输出一个整数,表示 B 在 A 中的出现次数。

Sample Input

zyzyzyz zyz

Sample Output

3

HINT

1≤A,B 的长度 ≤106 ,A 、B 仅包含大小写字母。

kmp模板套一下 

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
const  int maxn = 1e6 + 5;
int net[maxn];
char a[maxn],b[maxn];
int main()
{
    memset(net,0,sizeof(net));
    scanf("%s%s",a,b);
    int lena = strlen(a);
    int lenb = strlen(b);
    for(int i = 1 ; i < lenb;i++)
    {
        int j = i;
        while(j > 0)
        {
            j = net[j];
            if(b[j] == b[i])
            {
                net[i + 1] = j + 1;
                break;
            }
        }
    }
    int cnt = 0;
    for(int i = 0,j = 0;i < lena;i++)
    {
        if(j < lenb && b[j] == a[i])
        {
            j++;
        }
        else {
            while(j > 0)
            {
                j = net[j];
                if(a[i] == b[j])
                {
                    j++;
                    break;
                }
            }
        }
        if( j == lenb)
            cnt++;
    }
    cout<<cnt<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hzyhfxt/article/details/82226643