#include <stdio.h>
char target[1000001], tmp[1000000];
int backval[1000000];
int kmp()
{
int i, j, count = 0;
for(i = 0, j = backval[0] = -1; tmp[i];)
{
if(j == -1 || tmp[i] == tmp[j])
{
backval[i++] = j++;
}
else
{
j = backval[j];
}
}
for(i = j = 0, backval[i] = backval[i-1]; target[i]; )
{
if(j == -1 || target[i] == tmp[j])
{
i++;
j++;
if(tmp[j] == '\0')
{
count++, j = backval[j];
}
}
else
{
j = backval[j];
}
}
return count;
}
int main()
{
int n;
scanf("%d", &n);
while(n--)
{
scanf("%s%s", target, tmp);
printf("%d\n", kmp());
}
return 0;
}
Sunday
#include <stdio.h>
#include <string.h>
char text[1000000], patt[1000000];
void sunday()
{
int shift[123];
int i, j, k, pts = strlen(patt), tts = strlen(text);
char *tmp;
for(i = 'A', shift[0] = pts+1; i < 'z'; i++)
{
shift[i] = pts+1;
}
for(i = 0; i < pts; i++)
{
shift[patt[i]] = pts-i;
}
patt[pts] = '#';//end
for(i = 0, k = 0; i < tts-pts+1; i += shift[text[i+pts]])
{
if(text[i] == patt[0])
{
for(j = 1, tmp = text+i+1; *tmp == patt[j]; tmp++, j++)
{
;
}
if(j >= pts)
{
k++;
}
}
}
printf("%d\n", k);
}
int main()
{
int T;
scanf("%d", &T);
while(scanf("%s%s", text, patt) > EOF)
{
sunday();
}
return 0;
}
strstr
#include <stdio.h>
#include <string.h>
char text[100], patt[100];
int main()
{
int T, c;
char *p;
scanf("%d", &T);
for(c = 0; scanf("%s%s", text, patt) > EOF; )
{
for(p = text; (p = strstr(p, patt)) != NULL; ++p)
{
puts(p);
++c;
}
printf("%d\n", c);
}
return 0;
}