/*
* Prepared by junyisun @ CCNU
* E-MAIL: CCNUSJY@GMAIL.COM
* KMP algorithm C Code Description
*/
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
# Define max_s 101/* Maximum length of the master string is 100 */
# Define max_p 21/* the maximum length of the mode string is 20 */
Char s [max_s], p [max_p];/* s is the main string, and P is the mode string */
Int nextv [max_p];/* P nextv array */
Void init_nextv ()
{
Int I = 0, j =-1;
Int p_len;/* length of the mode string */
P_len = strlen (P );
Nextv [0] =-1;
While (I <p_len-1 ){
If (j =-1 | P [I] = P [J]) {
++ I; ++ J;
If (P [I]! = P [J]) nextv [I] = J;
Else nextv [I] = nextv [J];
}
Else J = nextv [J];
}
}
Int KMP ()
{
Int I = 0, j = 0, s_len, p_len;
S_len = strlen (s );
P_len = strlen (p );
While (I <s_len & j <p_len ){
If (j =-1 | s [I] = p [j]) {
I ++; j ++;
}
Else j = nextv [j];
}
If (j = p_len) return i-p_len;
Else return-1;
}
Int main ()
{
Int Index = 0;
Printf ("Enter the main string :");
Scanf ("% s", S );
Printf ("Enter the substring :");
Scanf ("% s", P );
Init_nextv ();
Index = KMP ();
If (index! =-1)
Printf ("matched successfully, matched position % d/N", index );
Else
Printf ("matching failed/N ");
System ("pause ");
Return 0;
}