[KMP] string matching-java code

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.