KMP算法之Java實現
相關代碼
各位前來看這篇文章,目的也就是獲取相關的代碼,這裏開門建山,給出可以使用的核心的代碼:
/**
* 用於字符串匹配的工具
*
* @author kevin
*
*/
public class StringKmp {
/**
* 用於計算匹配的位置(從頭到尾)
* @param str
* @param sub
* @return
*/
public static int kmp(String str, String sub) {
if(str == null || sub == null || str.length() == 0 || sub.length() == 0){
throw new IllegalArgumentException("str或者sub不能爲空");
}
int j = 0;
int[] n = next(sub);
for (int i = 0; i < str.length(); i++) {
while(j > 0 && str.charAt(i) != sub.charAt(j)){
j = n[j - 1];
}
if(str.charAt(i) == sub.charAt(j)){
j++;
}
if(sub.length() == j){
int index = i - j + 1;
return index;
}
}
return -1;
}
/**
* 用於生成部分匹配表
* @param sub
* @return
*/
private static int[] next(String sub) {
int[] n = new int[sub.length()];
int x = 0;
for (int i = 1; i < sub.length(); i++) {
while (x > 0 && sub.charAt(x) != sub.charAt(x)) {
x = n[x - 1];
}
if (sub.charAt(i) == sub.charAt(x)) {
x++;
}
n[i] = x;
}
return n;
}
}
演示代碼
public class Main {
public static void main(String[] args) {
String str = "BBC ABCDAB ABCDABCDABDE";
String sub = "ABCDAB";
int index = StringKmp.kmp(str, sub);
System.out.println("index-->"+index);
}
}
輸出結果
index-->4
KMP的理解
網絡中已經有了很好的相關解釋,本人水平有限,理解也不是很透徹,所以請移步到篇博客
代碼參考:請點擊這裏,可能需要梯子
結語
目前Java沒有提供關於KMP相應的jar包,可以將上述代碼直接當做工具類來使用。
轉載請標明出處http://blog.csdn.net/qq_26411333/article/details/51622537