. 1 #include <the iostream> 2 #include < String > . 3 #include <the cassert> . 4 the using namespace STD; . 5 . 6 void KMPStrMatching ( String S, String P, int * N, int & Start, int & len) . 7 { . 8 int J = 0 ; // index variable mode . 9 int I = 0 ; // index variable target 10 int pLen P.length = (); //The length of the pattern . 11 int tLen s.length = (); // length of the target 12 is 13 is the while (J <pLen && I < tLen) 14 { // repeated comparisons match 15 IF (J == - . 1 || S [I] == P [J]) 16 I ++, J ++ ; . 17 the else { 18 is . 19 J = N [J]; 20 is } 21 is IF (J> len) { 22 is len = J; Start = I- J; 23 is } 24 } 25 } 26 is 27 int * findNext ( String P) 28 { 29 int J, K; 30 int m = P.length (); // length m of the pattern P 31 is Assert (m> 0 ); // if m = 0, exit 32 int * = Next new new int [m]; // dynamic memory opened integer array 33 is Assert (Next =! 0 ;) // if fails open storage area exit 34 is Next [ 0 ] = - . 1 ; 35 = J 0; K = - . 1 ; 36 the while (J <M- . 1 ) 37 [ { 38 is IF (K == - . 1 || P [K] == P [J]) { 39 J ++; K ++; Next [J] = K ; 40 } 41 is the else 42 is K = Next [K]; // unequal KMP recursion is used to find the substrings inclusive 43 is } 44 is return Next; 45 } 46 is 47 int main () 48 { 49 String S1 = " fffaabcdeeeeeyyyyy "; 50 string s2 = "fqbcabcmxxabcdnn"; 51 52 int istart = 0, ilen =0; 53 for(int i=0; i<s2.length(); ++i){ 54 int start = 0, len = 0; 55 KMPStrMatching(s1,s2.substr(i),findNext(s2.substr(i)),start, len); 56 if(ilen<len){ 57 ilen = len; 58 istart = start; 59 } 60 } 61 62 cout<<s1.substr(istart, ilen)<<endl; 63 64 return 0; 65 }