字符串匹配算法:
利用最大相等的前后缀进行更好的匹配
#include <iostream>
#define int long long
using namespace std;
const int N = 1e6 + 10;
int m, n, ne[N], j;
char p[N], s[N];
signed main()
{
cin >> n >> p + 1 >> m >> s + 1; //p+1是指从第二个索引开始读入,即从p[1]开始
for (int i = 2, j = 0;i <= n;i ++) //找到上帝ne[i]
{
while (j && p[i] != p[j + 1]) j = ne[j];
if (p[i] == p[j + 1]) j ++;
ne[i] = j;
}
for (int i = 1, j = 0;i <= m;i ++) //开始匹配(让上帝帮我们优化)
{
while (j && s[i] != p[j + 1]) j = ne[j]; //不成功匹配则让上帝帮我们跳过不可能匹配的位置
if (s[i] == p[j + 1]) j ++;
if (j == n) //匹配成功找到最初的索引并输出
{
printf("%Ld ", i - j);
j = ne[j]; //进行下一轮匹配
}
}
return 0;
}
标签:匹配,int,long,char,算法,KMP
From: https://www.cnblogs.com/acing/p/18550253