//KMP算法实现
#include <iostream>
#include <string>
using namespace std;
//我承认KMP算法我搞得逻辑太复杂了
void KMP(char* a,char* b){
int next[10]={1};
int i,j,count1,count2,flag=1;
//计算模式串b的next[j]
next[0]=0;//如果第一位出错
next[1]=1;//如果第二位出错
//count1为左边的计数,count2为右边的计数
for(j=2;j<strlen(b);j++){
for(i=0;i<j;i++){
count1=i;
count2=1;
flag=1;
while(count1!=-1){
if(b[count1]==b[j-count2] && (count1!=j-count2))
flag++;
else
flag=1;
count1--;
count2++;
}
//flag为记号,如果有j能变得更大,那么赋值给next[j]
if(flag>next[j])
next[j]=flag;
}
}
//输出next[j]矩阵
for(int x=0;x<strlen(b);x++)
cout<<next[x]<<endl;
//主串和模式串进行匹配
i=j=0;
while(i<strlen(a)){
if(j==strlen(b)){
cout<<"找到匹配"<<endl;
return;
}
if(a[i]==b[j]){
i++;
j++;
}
else{
j=next[j];
if(j==0)
i++;
else
j--;
}
}
cout<<"未找到匹配"<<endl;
}
void main()
{
char a[]="ababex";
char b[]="abab";
KMP(a,b);
system("pause");
}