题意:给一串字符串,和一串模式串,求出原串可以剪出多少个模式串
思路:KMP匹配成功后返回模式串头继续匹配原串下一个字符
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
const int inf = 0x3f3f3f3f;
int n, m, fail[maxn], T, ans;
char s[maxn], p[maxn];
void getFail()
{
fail[0] = -1;
int k = -1, j = 0;
while (j < m - 1) {
if (k == -1 || p[j] == p[k]) {
j++;
k++;
fail[j] = k;
}
else
k = fail[k];
}
}
void kmp()
{
int i = 0, j = 0;
while (i < n) {
if (j == -1 || s[i] == p[j]) {
i++;
j++;
}
else
j = fail[j];
if (j == m) {
ans++;
j = 0;
}
}
}
int main()
{
// freopen("test.txt", "r", stdin);
while (~scanf("%s", s) && s[0] != '#') {
scanf("%s", p);
ans = 0;
n = strlen(s); m = strlen(p);
getFail();
kmp();
cout << ans << endl;
}
return 0;
}