#include <iostream>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <cmath>
using namespace std;
#define INF 0x3f3f3f3f
#define maxn 110000
const double PI = acos(-1.0);
typedef long long ll;
int Next[maxn];
char a[1000];
void get_next(char a[]);
int KMP(char a[], char b[]);
int main()
{
char b[maxn] ;
char a[maxn];
while(cin >> a >> b)
{
int sum = KMP(a, b);
cout << sum << endl;
}
return 0;
}
void get_next(char a[])
{
int i = 0, j = -1;
Next[0] = -1;
while(a[i] != '\0')
{
if(j == -1 || a[i] == a[j])
{
i++;
j++;
Next[i] = j;
}
else j = Next[j];
}
}
int KMP(char a[], char b[])
{
get_next(b);
int sum = 0;
int lena = strlen(a);
int lenb = strlen(b);
int i = 0, j = 0;
while(i < lena && j < lenb)
{
if(j == -1 || a[i] == b[j])
{
++i;
++j;
//此处开始与KMP常规算法不同,以此为找到模式串的标志并尽心回溯
if(j == lenb)
{
sum++;
j = Next[j];
}
}
else
j = Next[j];
}
return sum;
}
KMP算法求模式串在原串中出现的次数
原文作者:KMP算法
原文地址: https://blog.csdn.net/m0_38081836/article/details/78137453
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/m0_38081836/article/details/78137453
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。