行了,谢谢你啊
#include "iostream"
#include "stdlib.h"
#include "stdio.h"
#define N 255
using namespace std;
typedef char SString[N+1];
SString T,S;
void GetNext(SString T,int *next) {
int i=1,j=0;
next[i]=0;
while(i<T[0]){
if(j==0 || T[i]==T[j]){
++i;++j;
next[i]=j;
}
else j=next[j];
}
for(i=1;i<=T[0];i++){
cout<<next[i];
cout<<" ";
}
cout<<endl;
}
int IndexKMP(SString S,SString T,int *next) {
int i=1,j=1;
while(i<=S[0] && j<=T[0])
if(j==0||S[i]==T[j]){
++i;++j;
}
else j=next[j];
if(j>T[0]) return (i-j+1);
else return 0;
}
void all(SString S){
int i=0,j=1;
while(S[j]!=NULL) {
j++; i++;
}
S[0]=i;
}
void main(){
int k,i;
int next[N];
cout<<"请输入字符串S:"<<endl;
gets(&S[1]);
all(S);
cout<<"请输入字符串T:"<<endl;
gets(&T[1]);
all(T);
cout<<"next值分别为:";
GetNext(T,next);
k=IndexKMP(S,T,next);
cout<<"在第";
cout<<k;
cout<<"个字符发现匹配"<<endl;
}