#include <iostream>
#include <string>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
bool getNext(string T,int* next);
bool KMP(string T , string S , int *next , int &loc);
int main(int argc, char** argv) {
string T,S;
S = "0abbcababcaabaabcabcbc";
T = "0abaabcabc";
int* next = new int[10];
int loc;
getNext(T,next);
for(int i=1;i<T.length();i++){
cout<<next[i];
}
cout<<"\n";
if( KMP(T,S,next,loc) )
cout<<"\nloc:: "<<loc;
else
cout<<"\n-1";
return 0;
}
bool getNext(string T,int *next){
next[1] = 0;
int j = 0;
int i = 1;
while( i < T.length()){
/**
如果Ti=Tj 则表明
1到k位置前的串 和 k到j的串相同
则有 next[j+1] = next[j]+1
如果Ti != Tj 则表明
1到k位置的串 和 k到j的串不相同
则有 next[j+1] = next[
**/
if(j==0 ||T.at(i) == T.at(j) ){
++i;
++j;
next[i] = j ;//如果Ti = Tj 则 next[j+1] = next[j] + 1;
}
else
j = next[j];//否则 j = next[j]
}
}
bool KMP(string T,string S,int *next, int &loc){
int i = 1;
int j = 1;
while(i<S.length() && j< T.length()){
if(j ==0 ||S.at(i) == T.at(j)){
++i;
++j;
}else{
j = next[j];//模式串右移
}
}
if(j = T.length()){
loc = i - T.length();
return true;
}else{
return false;
}
}