用nextval[]改进next[]
还有,代码真美,看了好久
#include<stdio.h>
#define MAXSIZE 100
#include<iostream>
using namespace std;typedef struct
{char data[MAXSIZE];int length;
}SqString;void StrAssign(SqString &s,char cstr[])
{int i;for(i=0;cstr[i]!='\0';i++)s.data[i]=cstr[i];s.length=i;
}void GetNextval(SqString t,int nextval[])
{int j=0,k=-1;nextval[0]=-1;while(j<t.length){if(k==-1||t.data[j]==t.data[k]){j++;k++;if(t.data[j]!=t.data[k]){nextval[j]=k;}else nextval[j]=nextval[k];}else k=nextval[k];}}int KMPIndex1(SqString s,SqString t)
{int nextval[MAXSIZE],i=0,j=0;GetNextval(t,nextval);while(i<s.length&&j<t.length){if(j==-1||s.data[i]==t.data[j]){i++;j++;}elsej=nextval[j];}if(j>=t.length)return (i-t.length);else return -1;}int main()
{SqString t,p;StrAssign(t,"aaadaaadaaaad");StrAssign(p,"aaaad");cout<<KMPIndex1(t,p)<<endl;
}