String matching algorithms are familiar to everyone. The kmp algorithm is a classic algorithm. However, the essence of the kmp algorithm is to look for the next [] array.
It mainly solves the next [] of matching strings.
[Java]
Package qyq. Algorithm. KMP;
/**
* KMP string matching
* @ Author qi
* @ Creation 2012-8-14
*/
Public class Kmp {
Public static void main (String [] args ){
String S = "abcdthabc ";
String T = "bcdmmn ";
Int lenS = S. length ();
Int lenT = T. length ();
Int next [] = new int [lenT + 1];
GetNext (T, next); // next [] array Solution
For (int I = 0; I <next. length; I ++) {// print the next Array
System. err. println (next [I]);
}
Int kmp = K_next (S, T, lenS, lenT, next );
System. err. println ("first matched location:" + kmp );
}
Public static void getNext (String T, int next []) {
Int j = 1, k = 0;
Next [1] = 0;
While (j <T. length ()){
If (k = 0 | T. charAt (j) = T. charAt (k )){
J ++;
K ++;
Next [j] = k;
} Else {
K = next [k];
}
}
}
Public static int K_next (String S, String T, int lenS, int lenT, int next []) {
Int I = 0, j = 0;
While (I <lenS & j <lenT ){
If (j = 0 | S. charAt (I) = T. charAt (j )){
I ++;
J ++;
} Else {
J = next [j];
}
}
If (j = lenT ){
Return I-lenT;
}
Return-1;
}
}
Author; qitian0008