Substring search
Topic link: ybt efficient advanced 2-3-1
Topic
Find the number of occurrences of a string in another string.
Ideas
This question seems to be a KMP template question.
Just press the KMP template and type it again.
Code
#include<cstdio>
#include<cstring>
using namespace std;
int an, bn, ans, fail[1000001], j;
char a[1000001], b[1000001];
int main() {
scanf("%s", a + 1);
scanf("%s", b + 1);
an = strlen(a + 1);
bn = strlen(b + 1);
j = 0;
for (int i = 2; i <= bn; i++) {
while (j && b[i] != b[j + 1]) j = fail[j];
if (b[i] == b[j + 1]) j++;
fail[i] = j;
}
j = 0;
for (int i = 1; i <= an; i++) {
while (j && a[i] != b[j + 1]) j = fail[j];
if (a[i] == b[j + 1]) j++;
if (j == bn) {
ans++;
}
}
printf("%d", ans);
return 0;
}