字符串匹配
#include <iostream>
#include <cstdio>
#include <cstring>
const int MAX = 1e6 + 5;
int next[MAX];
char str[MAX], p[MAX];
int res;
void getNEXT(char* p, int* next)
{
next[0] = -1;
int k = -1, j = 0;
int lenth = strlen(p);
while (j != lenth)
{
if (k == -1 || p[k] == p[j])
{
++k;
++j;
if (p[j] != p[k])
next[j] = k;
else
next[j] = next[k];
}
else
{
k = next[k];
}
}
}
int kmp(char* p, char* str)
{
getNEXT(p, next);
int lenth1 = strlen(str);
int lenth2 = strlen(p);
int i = 0, j = 0;
while (i < lenth1)
{
if (j == -1 || str[i] == p[j])
{
++i;
++j;
if (j == lenth2)
{
res++;
j = next[j];
//std::cout << j << std::endl;
}
}
else
{
j = next[j];
}
}
return res;
}
int main()
{
int t, cas = 0;
scanf("%d", &t);
while (t--)
{
res = 0;
scanf("%s%s", str, p);
memset(next, 0, sizeof(next));
printf("Case %d: %d\n", ++cas, kmp(p, str));
}
return 0;
}