#include <iostream>
#include <string>
using namespace std;
int main() {
int wordLen=37;
int strLen=7;
string word="bacbababadababacambabacaddababacasdsd";
string str="ababaca";
string subStr;
int matchLength[strLen];
matchLength[0]=0;
int next[strLen];
next[0]=0;
int m,n,flag;
for(int i=1;i<strLen;i++){
for(int j=0;j<=i;j++){
subStr[j]=str[j];
}
for(int k=0;k<=i;k++){
cout<<subStr[k];
}
m=0;n=1;flag=0;
while(flag<=i){
do{
if(subStr[m]==subStr[n]){
if(m==0){
flag=n;
}
m++;
n++;
}else{
n++;
}
}while(n<=i);
if(n-flag==m){
break;
}else{
flag++;
n=flag;
m=0;
}
}
cout<<"\t"<<m<<endl;
matchLength[i]=m;
}
cout<<"MatchLength[]:\t";
for(int i=0;i<strLen;i++){
cout<<matchLength[i]<<" ";
}
cout<<endl;
for(int i=1;i<strLen;i++){
next[i]=matchLength[i-1];
}
cout<<"Next[]:\t\t";
for(int i=0;i<strLen;i++){
cout<<next[i]<<" ";
}
cout<<endl;
int x=0;
int index=-1;
for(int i=0;i<wordLen;i++){
cout<<"word["<<i<<"]:"<<word[i]<<"\tstr["<<x<<"]:"<<str[x]<<endl;
if(word[i]!=str[x]&&x>0){
x=next[x];
cout<<"word["<<i<<"]:"<<word[i]<<"\tstr["<<x<<"]:"<<str[x]<<endl;
}
if(word[i]==str[x]){
if(x==strLen-1){
index=i-strLen+1;
cout<<"index:"<<index<<endl;
x=0;
}else{
x++;
}
}
}
return 0;
}