转载https://blog.csdn.net/LEE18254290736/article/details/77278769
https://blog.csdn.net/yearn520/article/details/6729426这里的next讲解特别详细清楚
#include<iostream>
#include<vector>
#include<string>
using namespace std;
//求next数组
void solve_next(char *a, int n, int *next){
next[0] = 0;//初始化
for (int i = 1; i < n; i++){
int k = next[i - 1];
while (a[i] != a[k] && k != 0){//寻找子对称
k = next[k - 1];
}
if (a[i] == a[k])
{
//找到了子对称
next[i] = k + 1;
}
else{
//找不到
next[i] = 0;
}
}
}
int kmp_search(char *src,int s_len,char* pat,int p_len,int *next){
int i = 0, j = 0;
while (i < s_len&&j < p_len){
if (j==-1||src[i] == pat[j]){
i++; j++;
}
else{
j = next[j]-1;
}
}
if (j >= p_len)return i - p_len + 1;//返回的是匹配的第i位
else return -1;
}
int main(){
char a[16] = { 'a', 'g', 'c', 't', 'a', 'g', 'c', 'a', 'g', 'c', 't', 'a', 'g', 'c', 't','g' };
int next[16];
solve_next(a, 16, next);
for (int i = 0; i < 16; i++)
cout << next[i] << " ";
cout << endl;
char pat[5] = { 'a', 'b', 'a', 'b', 'c' };
char src[13] = { 'a', 'b', 'a', 'b','e', 'e', 'b', 'a', 'b', 'c', 'b', 'c', 'c' };
int next1[5];
solve_next(pat, 5, next1);
for (int i = 0; i < 5; i++)
cout << next1[i] << " ";
cout << endl;
cout << kmp_search(src, 13, pat, 5, next1);
cout << endl;
system("pause");
return 0;
}