题目连接:
分析
这里所要求的一个源字符串中能匹配多少个目标字符串,所以说在KMP算法的基础上需要改进一下,在j到达目标字符串的结尾的时候,即 j==strlen(目标串)时,使用 j=nex[j-1]来找到目标串的最长重复子串,其次呢,在刚开始的时候,while循环中全部使用strlen()进行判断的,所以总是超时,应该在while循环之外先使用 len存放strlen,这样才不会超时。
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int MAXN = 1000005;
char t[MAXN],w[10005];
int nex[10005],test,ans;
void GetNext(char *ch)
{
nex[0] = -1;
int k = -1,j=0;
int len = strlen(ch);
while(j < len)
{
if(k == -1 || ch[k] == ch[j])
nex[++j] = ++k;
else
k = nex[k];
}
}
int main()
{
scanf("%d",&test);
while(test--)
{
ans = 0;
memset(nex,0,sizeof(nex));
scanf("%s",w);
scanf("%s",t);
GetNext(w);
int i = 0,j = 0;
int sourLen = strlen(t),desLen = strlen(w); //提前执行strlen,否则在while循环中执行会超时
while(i <= sourLen)
{
if(j == desLen)
{
ans++;
j = nex[j-1];
i--;
}
if(i == sourLen) break;
if(j==-1 || t[i] == w[j])
{
++i;
++j;
}
else
j = nex[j];
}
printf("%d\n",ans);
}
return 0;
}