void GetNext(string T, int next[])
{
int length = T.length();
int j = 0, k = -1;
next[0] = -1;
while ( j < length - 1 )
{
if ( -1 == k || T[j] == T[k] )
{
++j;
++k;
next[j] = k;
}
else
{
k = next[k];
}
}
}
int KMP(string S, string T, int pos)
{
int sLength = S.length();
int tLength = T.length();
int j = pos, k = 0;
int* next = new int[tLength];
GetNext(T, next);
while ( j < sLength && k < tLength )
{
if ( -1 == k || S[j] == T[k] )
{
++j;
++k;
}
else
{
k = next[k];
}
}
if ( k >= tLength )
{
return j - tLength;
}
else
{
return -1;
}
}
int main(int karc, char* karv[])
{
string S = "abcadefabcabxabcad";
string T = "abcabx";
cout << "Position = " << KMP(S, T, 0) << endl;
char ch1= getchar();
return 0;
}