Implement KMP algorithm in Java

Source: Internet
Author: User

// KMP. Java
/**
* @ Author feixiang KMP Algorithm
* The characters to be checked and the next array start from unit 0.
* The first value of the next array is-1, which means that if you want to compare the next value with the first value of the comparison string, you need to move the original string.
* One more step is required to know that the previous step is missing.
*/
Package first;

Public class KMP {
Public static void main (string [] ARGs)
{
String A = "aaabcabcdeadfskdljfa; lskjdf; kljsdkjfeilskjf ";
String B = "abcabcde ";
Int c = kmp_find (a, B, 0 );
System. Out. println (C );
}
Static int [] getnext (string fidstr)
{
Int Len = fidstr. Length ();
Int next [] = new int [Len];
Int J =-1, I = 0;
Next [0] =-1;
While (I <len-1) // here this minus 1 is necessary, because I relates to the previous one to calculate next
{
If (-1 = j | fidstr. charat (j) = fidstr. charat (I ))
{
++ I; ++ J;
If (fidstr. charat (j) = fidstr. charat (I ))
Next [I] = next [J];
Else
Next [I] = J;
}
Else
{
J = next [J];
}
}
Return next;
}
Static int kmp_find (string surstr, string fidstr, int POS)
{
Int next [] = getnext (fidstr );
Int J = 0;
Int I = Pos;
While (j <fidstr. Length () & I <surstr. Length ()-fidstr. Length () + 1)
{
If (-1 = j | fidstr. charat (j) = surstr. charat (I ))
{
J ++; I ++;
}
Else
{
J = next [J];
}
}
If (j = fidstr. Length ())
{
Return i-FidStr.length ();
}
Else
{
Return-1;
}
}
}

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.