KMP算法
package KMP;
//KMP算法
public class KMP {
public static void main(String[] args) {
String str1="BBC ABCDAB ABCDABCDABDE";
String str2="ABCDABD";
int[] next=kmpNext(str2);
System.out.println(kmp(str1, str2, next));
}
public static int kmp(String str1,String str2,int[] next) {
for (int i = 0,j = 0; i < str1.length(); i++) {
//kmp核心算法
while (j>0 && str1.charAt(i)!=str2.charAt(j)) {
j=next[j-1];
}
if (str1.charAt(i)==str2.charAt(j)) {
j++;
}
if (j==str2.length()) {
return i-j+1;
}
}
return -1;
}
//计算匹配表数组
public static int[] kmpNext(String dest) {
int[] temp=new int[dest.length()];
temp[0]=0;
for (int i = 1,j=0; i < temp.length; i++) {
//kmp核心算法
while (j>0 && dest.charAt(i)!=dest.charAt(j)) {
j=temp[j-1];
}
if (dest.charAt(i)==dest.charAt(j)) {
j++;
}
temp[i]=j;
}
return temp;
}
}