image-20231213230121396

 image-20231213233014666

This time p [i]= P [j+1], when the array does not match, the j=next [j] statement is executed. Because of the mismatch, j will go back until j goes back to 0.

The code of kmp is as follows

 one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
 //Substring and long string subscripts start from 1
bool kmp ( char *s, int l1, char *p, int l2) {
/*Find next array*/
for ( int i= two , j= zero ; i<=l1;i++){
while (j&&p[i]!=p[j+ one ]) j=next[j];
if (p[i]==p[j+ one ]) j++;
next[i]=j;
}
/*Make string pairing*/
for ( int i= zero ; i<l1;i++){
while (j<l2&&s[i]==p[j+ one ]) j++;
if (j==l2){
cout << "Matching succeeded" << endl ;
return true ;
}
j=next[j];
}
}