1 # include <stdio. h> 2 # include <string. h> 3 # include <stdlib. h> 4 # define n 100005 5 char S1 [2 * n], S2 [N]; 6 int next [N], L1, L2; 7 8 void get_next (char * STR, int Len) 9 {10 int I =-1, j = 0; 11 next [0] =-1; // assign the initial value 12 Len = strlen (STR) to next [0]; 13 if (j <Len) 14 {15 if (I =-1 | STR [I] = STR [J]) 16 {17 I ++; 18 J ++; 19 if (STR [I]! = STR [J]) // when I =-1, 20 next [J] = I; 21 else22 next [I] = next [J]; 23} 24 else25 I = next [I]; 26} 27} 28 void KMP (char * str1, char * str2) 29 {30 int I = 0, j = 0, len1, len2; 31 len1 = strlen (str1); 32 len2 = strlen (str2); 33 while (I <len1 & J <len2) 34 {35 if (j =-1 | str1 [I] = str2 [J]) 36 {37 I ++; 38 J ++; 39} 40 else41 J = next [J]; 42} 43 If (j> = len2) 44 printf ("Yes \ n "); 45 else46 printf ("NO \ n"); 47} 48 49 main () 50 {51 int I; 52 while (SCAN F ("% s", S1 )! = EOF) 53 {54 L1 = strlen (S1); 55 for (I = 0; I <L1; I ++) 56 S1 [L1 + I] = S1 [I]; 57 scanf ("% s", S2); 58 L2 = strlen (S2); 59 get_next (S2, L2 ); // use void to define 60 KMP (S1, S2) for functions without return values; 61} 62} 63 64 65
Let's take a look at this link (http://www.cnblogs.com/dolphin0520/archive/2011/08/24/2151846.html) for a clear and intuitive explanation of the KMP Algorithm