The next sequence, which represents the maximum matching length of the substring's prefix. For example, String c[], Next[i] represents the maximum matching length of the prefix to the suffix in substring c[0. i].
For example, if the substring is abcuab, its prefix is a, AB, ABC, ABCU, Abcua, suffix is b, AB, UAB, CUAB, BCUAB, where the matching maximum substring is AB, the length is 2.
Calculate Next's value by definition
Public Static int[] Getnexts (Char[] TT) { int[] nexts =New int[Tt.length]; nexts[0] = 0; //from 1 to the end, calculate next for(inti = 1; i < tt.length; i++) { //in a given substring, the maximum length value when recording matched for(intj = 0; J < I; J + +) { Booleanmatched =true; //using K, compare the characters from 0 to J and from I-j to I for equality, noting that the subscript is moving from small to large for(intk = 0; K <= J; k++) { if(Tt[k]! = tt[i-j+K]) {matched=false; Break; } } //match, record maximum length if(matched) {intLength = j + 1; if(Nexts[i] <length) nexts[i]=length; } } } returnnexts; }
The improved method, which sequentially records the value of next in the traversal, reduces the loop by many
/*** Use only two starting subscript to calculate and record next sequence * *@paramTT *@return */ Public Static int[] GetNexts2 (Char[] TT) { int[] nexts =New int[Tt.length]; nexts[0] = 0; //prefix start subscript intprefix = 0; //suffix start subscript intsuffix = prefix + 1; //Match Length intLen = 0; while(Suffix <tt.length) {if(Tt[prefix] = =Tt[suffix]) { //if it matches, the current next maximum value is recorded and the prefix and suffix subscript are moved to a largeprefix++; Len++; if(Nexts[suffix] <len) Nexts[suffix]=Len; } Else { //if it does not match, the current length is zero, and the prefix returns to the beginning, and the suffix still goes backwards.Len = 0; Prefix= 0; } suffix++; } returnnexts; }
KMP algorithm for matching strings