Home > other >  KMP algorithm kmpNext method in a while loop can change to if have a counterexample is not directly
KMP algorithm kmpNext method in a while loop can change to if have a counterexample is not directly

Time:09-20

 
Public class KmpAlgorithm {
Public static void main (String [] args) {

Strings str1="\ t C C/tC/tC/tC/tC/tC/tC/tC/tA, tA, tA, tA, tB, tA, tA, tA, tA, tB \ t A, tB and tB/tC/tA, tB and tB, tC, tA, tA, tA, tB and tB/tC/tA, tB and tB"
Replace (" \ t ", "")
Replace (" ", "");
String str2="AAABAAAAB";
Int [] next=kmpNext (str2);
for (int i=0; I System. The out. Print (str2. CharAt (I) + "\ t");
}
System.out.println();
for (int i=0; I System. The out. Print (next [I] + "\ t");
}
System.out.println();
System. The out. Println ("====================");
Int index=kmpSearch (str1 str2, next);
System. The out. Println (index);
}

Public static int kmpSearch (String str1, String str2, int [] next) {
For (int I=0, j=0; I
While (j> 0 & & str1 charAt (I)!=str2. CharAt (j)) {
J=next [j - 1);
}
If (str1. CharAt (I)==str2. The charAt (j)) {
j++;
}
If (j==str2 length ()) {
The return I - (j - 1);
}
}
return -1;
}

Public static int [] kmpNext (String dest) {
Int [] next=new int [dest. Length ()];
For (int I=1, j=0; I While (j> 0 & & dest charAt (I)!=dest. CharAt (j)) {
J=next [j - 1);
}
If (dest. CharAt (I)==dest. The charAt (j)) {
j++;
}
next[i]=j;
}
Return next;
}
}


  • Related