// 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;
}
}
}