题意:两个字符串,模式串和目标串,输出每个模式串在目标串中出现次数,可重叠。
题解:kmp模板题,每次找到后数量加一。
#include <stdio.h>
#include <string.h>
const int N = 1000005;
char p[N], t[N];
int next[N], len1, len2;
void getnext() {
int pp = -1, k = 0;
next[0] = -1;
while (k < len2) {
if (pp == -1 || p[pp] == p[k]) {
k++;
pp++;
next[k] = pp;
}
else
pp = next[pp];
}
}
int kmp() {
int pp = 0, tt = 0, count = 0;
while (tt < len1) {
if (pp == -1 || t[tt] == p[pp]) {
pp++;
tt++;
}
else
pp = next[pp];
if (pp == len2)
count++;
}
return count;
}
int main() {
int cases;
scanf("%d", &cases);
while (cases--) {
scanf("%s", p);
scanf("%s", t);
len1 = strlen(t);
len2 = strlen(p);
getnext();
int ans = kmp();
printf("%d\n", ans);
}
return 0;
}