#include<iostream> #include<string.h> using namespace std; #define MAXLEN 255 //预定义最大串长为255 typedef struct { char ch[MAXLEN]; int length; } SString; typedef struct { char *ch; int length; } HString; void copy(SString *T,char*s) { int length=strlen(s); for(int i=0; i<length; i++) { (*T).ch[i+1]=s[i]; } (*T).length=length; } int Index(SString S, SString T) { int i=1, j=1; while(i<=S.length&&j<=T.length ) { if (S.ch[i] ==T.ch [j] ) { ++i; ++j; //继续比较后继字符 } else { i=i-j+2; j=1; //指针后退重新开始匹配 } } if(j>T.length) return i-T.length; else return 0; } void get_next(SString T,int next[]) { int i=1,j=0; next[1]=0; while(i<T.length ) { if (j==0||T.ch[i]==T.ch[j]) { ++i ; ++j; next[i]=j; //若Pi=Pj ,则next[j+1] =next[j]+1 } else j=next[j]; //否则令j=next[j]循环继续 } } int Index_KMP(SString S, SString T, int next[]) { int i=1,j=1 ; while(i<=S.length&&j<=T.length) { if (j==0||S.ch[i]==T.ch [j]) { ++i; ++j;//继续比较后继字符 } else j=next [j];//模式串向右移动 } if (j>T.length ) return i-T.length; else return 0; } void get_nextval(SString T ,int nextval[]) { int i=1, j=0; nextval[1]=0; while (i<T.length ) { if (j==0||T.ch [i]==T.ch[j]) { ++i,++j; if (T.ch[i]!=T.ch[j]) nextval[i]=j ; else nextval [i] =nextval[j]; } else j=nextval[j]; } } int main() { SString S,T,K; char *s1="12345678"; char *s2="234"; copy(&S,s1); copy(&T,s2); char *s3="aabaabaabaac"; copy(&K,s3); int next_val[13]; // get_nextval(K,next_val); get_next(K,next_val); for(int i=1;i<=12;i++) { cout<<next_val[i]<<" "; } cout<<endl; cout<<Index_KMP(S, T, next_val); // cout<< Index(S,T); return 0; }