First, you need to understand the BF brute force matching algorithm. This algorithm sets a pointer for each string, and then the two pointers are moved back at the same time. If there is any mismatch,The primary string pointer returns to the next position before the start and backward shift, and the pattern string pointer returns to the beginning..
To compare the KMP algorithm, we also set two pointers, and then the two pointers are moved back at the same time. If the two pointers do not match,The master string pointer remains unchanged, and the mode string pointer traces back to a certain distance.. The number of pattern string pointers Backtracking is hard to understand for the first time when you look at the KMP algorithm. In fact, think carefully,The prefix and suffix of the pattern string are actually being matched. When P [k]! = P [J] is a mismatch, so the prefix pointer needs to be traced back, so the last K = next [k].
/*** Source code name: KMP. java * Date: 2014-09-03 * program function: KMP algorithm * copyright: [email protected] * a2bgeek */public class KMP {public int [] getnext (string in) {int [] Next = new int [in. length ()]; Int J = 0; int K =-1; next [J] = K; while (j <next. length-1) {If (k =-1 | in. charat (K) = in. charat (j) {J ++; k ++; next [J] = K;} else {k = next [k] ;}} for (int I: Next) {system. out. print (I + "");} system. out. println (); return next;} public int KMP (string S, string p) {int I = 0; Int J = 0; int [] Next = getnext (P ); while (I <S. length () & J <p. length () {If (j =-1 | S. charat (I) = P. charat (j) {I ++; j ++;} else {J = next [J] ;}} if (j = P. length () {return 1 ;}else {return-1 ;}} public static void main (string [] ARGs) {KMP = new KMP (); string S = "acbfdfjkdhg"; string P = "dfdj"; system. out. println (KMP. KMP (S, P ));}}
[Data structure and algorithm] string matching KMP Algorithm