>Link
ybtoj子串查找
>解题思路
一道kmp的模板题
>代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 1000010
using namespace std;
int p[N], la, lb, ans;
string a, b;
int main()
{
cin >> a >> b;
la = a.size(), lb = b.size();
a = " " + a, b = " " + b;
int j = 0;
p[1] = 0; //p表示b串中最长相同前缀后缀
for (int i = 1; i < lb; i++)
{
while (j > 0 && b[j + 1] != b[i + 1])
j = p[j]; //不能继续匹配的话,缩短长度(有前后相同性)
if (b[j + 1] == b[i + 1]) j++;
p[i + 1] = j;
} //预处理:b串自己与自己匹配
j = 0;
for (int i = 0; i < la; i++)
{
while (j > 0 && a[i + 1] != b[j + 1])
j = p[j];
if (a[i + 1] == b[j + 1]) j++;
if (j == lb)
{
ans++; //记录答案
j = p[j];
}
}
printf ("%d", ans);
return 0;
}