#include"iostream"
#include"stdio.h"
#include"stdlib.h"
#include"string.h"
#define maxSize 20
using namespace std;
struct Str{
int len;
char *c;
};
void get_nextval(Str sub,int nextval[]){
int i=1;
int j=0;
nextval[1]=0;
while(i<=sub.len){
if(j==0||sub.c[i]==sub.c[j]){
++i;
++j;
if(sub.c[i]!=sub.c[j]){
nextval[i]=j;
}
else{
nextval[i]=nextval[j];
}
}
else{
j=nextval[j];
}
}
}
int get_pos(Str s,Str sub,int nextval[]){
int i=1;
int j=1;
while(i<=s.len&&j<=sub.len){
if(j==0||s.c[i]==sub.c[j]){
++i;
++j;
}
else{
j=nextval[j];
}
}
if(j>sub.len){
return i-sub.len;
}
else return -1;
}
int main(){
int nextval[maxSize];
Str s;
Str sub;
s.len=sub.len=0;
char c1[]={'A','B','A','B','C','A','B','C','A','C','B','A','B'};
char c2[]={'A','B','C','A','C'};
s.len=sizeof(c1);
sub.len=sizeof(c2);
s.c=(char *)malloc(sizeof(c1)+2);
sub.c=(char *)malloc(sizeof(c2)+2);
for(int i=1;i<=s.len;i++){
s.c[i]=c1[i-1];
}
for(int i=1;i<=sub.len;i++){
sub.c[i]=c2[i-1];
}
get_nextval(sub,nextval);
int pos=get_pos(s,sub,nextval);
cout<<pos;
return 0;
}
运行结果6
注:这里的nextval数组为KMP算法的改进版,减少了模式串的回溯次数