[Cpp]
# Include "stdafx. h"
# Include <iostream>
Using namespace std;
Void get_next (char * t, int next []) {
Int t_len = strlen (t );
Int I = 0; // solve each next [I]
Next [0] =-1; // recursive basic condition, and then solve next [I + 1]
Int j =-1; // backward recursive position subscript
/*
Next [I] = k => T0.... Tk-1 = Ti-k... Ti-1
Next [I + 1]
1> If t0.. Tk-1Tk = Ti-k... Ti-1Ti => next [I + 1] = k + 1 = next [I] + 1;
2> Tk <> Ti, next [k] = k ', if Ti = Tk '=> next [I + 1] = k' + 1 = next [k] + 1 = next [next [I] + 1;
3> recursive the last case in sequence: next [I + 1] = next [0] + 1 = 0, that is
*/
While (I <t_len)
{
If (j =-1 | t [I] = t [j]) // j =-1 proves that it does not match t [0, next [I + 1] = 0
{
I ++;
J ++;
Next [I] = j;
}
Else
{
J = next [j];
}
}
}
Int KMP (char * s, char * t ){
Int s_len = strlen (s );
Int t_len = strlen (t );
Int I = 0;
Int j = 0;
Int * next = new int [t_len];
Get_next (t, next );
If (t_len> s_len) return-1;
While (I <s_len & j <t_len ){
If (j =-1 | s [I] = t [j]) {
I ++;
J ++;
}
Else {
J = next [j];
}
} // End while
If (j> = t_len)
Return I-j;
Else
Return-1;
}
Int main (void)
{
Char * s = "abcdasdefghijklmnefgh ";
Char * t = "efgh ";
Cout <KMP (s, t) <endl;
Return 0;
}