题目描述:给定一个字串,求这个字串在母串中出现的次数。(注意这里的匹配是一种类似于贪婪匹配的模式,意思就是如果当前的字符被在一次匹配成功了,他依然可以参与下一次的匹配).这是一个KMP的裸题,KMP算法就不再说了,知道它的思想:使用字串本身的信息来简化匹配的次数,最重要的是NEXT数组的理解。下面给出具体的实现的代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
#define ll long long
const int MAXW = 10001, MAXT = 1000001;
char W[MAXW], T[MAXT];
int Next[MAXW];
int lenW, lenT;
#pragma warning(disable:4996)
void getNext(int lenW)
{
int i = 0, j = -1;
Next[i] = -1;
while (i<lenW) {
if (j == -1 || W[i] == W[j]) {
Next[++i] = ++j;
}
else j = Next[j];
}
}
int kmp(int pos, int lenW, int lenT)
{
int i = pos, j = 0, ans = 0;
while (i<lenT)
{
if (T[i] == W[j] || j == -1) ++i, ++j;
else j = Next[j];
if (j == lenW) {
ans++;
j = Next[j - 1];
i--;
}
}
return ans;
}
int main()
{
int n;
scanf("%d", &n);
while (n--)
{
scanf("%s%s", W, T);
lenW = strlen(W);
lenT = strlen(T);
getNext(lenW);
printf("%d\n", kmp(0, lenW, lenT));
}
return 0;
}