给两个字符串,在目标串里找到模式串的个数。
#include <cstdio>
#include <cstring>
char text[1000005];
char word[10005];
int next[10005];
//改进后的next数组,速度更快
void get_next()
{
int j = -1, i = 0;
next[0] = -1;
while(word[i] != '\0')
{
if(j == -1 || word[j] == word[i])
{
j++;
i++;
if(word[j] == word[i])
next[i] = next[j];
else
next[i] = j;
}
else
j = next[j];
}
}
int KMP()
{
get_next();
int j = 0, i = 0;
int ans = 0;
int wlen = strlen(word);
int tlen = strlen(text);
while(i < tlen && j < wlen)
{
if(j == -1 || text[i] == word[j])
{
i++;
j++;
}
else
j = next[j];
if(j == wlen)
{
ans++;
j = next[j];
}
}
return ans;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(next,0,sizeof(next));
scanf("%s%s",word,text);
printf("%d\n",KMP());
}
}