Directly connected to the previous code:
1 //KMP Algorithm2 Public classKMP {3 4 //gets the next array method, based on the given string5 Public Static int[] GetNext (String sub) {6 7 intj = 1, k = 0;8 int[] Next =New int[Sub.length ()];9Next[0] =-1;//This is a rule .TenNEXT[1] = 0;//This is a rule . One // A while(J < Sub.length ()-1) { - if(Sub.charat (j) = =Sub.charat (k)) { -Next[j + 1] = k + 1; theJ + +; -k++; -}Else if(k = = 0) { -Next[j + 1] = 0; +J + +; -}Else { +K =Next[k]; A } at - } - returnNext; - } - - //The KMP algorithm is used to obtain pattern matching according to the given main string and substring . in Public Static intKMP (String src, string sub) { - to //first generate a pattern string sub Next[j] + int[] Next =GetNext (sub); - inti = 0, j = 0, index =-1; the while(I < Src.length () && J <sub.length ()) { * if(Src.charat (i) = =Sub.charat (j)) { $i++;Panax NotoginsengJ + +; -}Else if(j = = 0) { thei++; +}Else { Aj =Next[j]; the } + } - $ //get the position index to start matching $ if(J = =sub.length ()) { -index = i-sub.length (); - } the returnindex; - }Wuyi}
//
1 //testing of the KMP algorithm2 Public classTest {3 /**4 * @paramargs5 */6 Public Static voidMain (string[] args) {7String src = "Aaaaaaab";8String sub = "Abcdabdabd";9 int[] Next =Kmp.getnext (sub);Ten //int[] Next = LENGTHKMP (Sub.tochararray ()); One for(intI:next) { ASystem.out.print (i + "");//-1 0 1 2 3 - } - the //System.out.println (); - //System.out.println (KMP.KMP (src, sub)); - } - + //An algorithm that complements the discussion of prefix suffixes in the previous article to get a partial matching array - Public Static int[] LENGTHKMP (Char[] Mchar) { + int[] Fixnum =New int[mchar.length]; A for(inti = 1, j = 0; i < mchar.length; i++) { at if(Mchar[j] = =Mchar[i]) { -Fixnum[i] = j + 1; -J + +; -}Else if(J > 0) { -j = 0; -I-=J; in } - } to //return [0, 0, 0, 0, 1, 2, 0, 1, 2, 0]abcdabdabd + returnFixnum; - } the}
Java data structure string pattern matching algorithm---KMP algorithm 2