本文是字符串匹配的KMP算法实现:
kmp算法的介绍可以查看阮一峰的这篇博客:http://ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html
package algorithm;
public class Kmp {
private String totalStr;
private String matchStr;
// 部分匹配表
private int[] matchTable;
// 匹配结果
private boolean result;
// 匹配到的起始位置
private int index;
public Kmp(String totalStr, String matchStr) {
this.totalStr = totalStr;
this.matchStr = matchStr;
this.matchTable = matchTable(matchStr);
search(totalStr, matchStr, matchTable);
}
/**
* 计算部分匹配表
* */
private int[] matchTable(String str) {
if ("".equals(str) || null == str) {
return null;
} else {
if (str.length() == 1) {
matchTable = new int[0];
} else {
String[] prefix = null;
String[] suffix = null;
int matchNum = 0;
matchTable = new int[str.length()];
matchTable[0] = 0;
for (int i = 1; i < str.length(); i++) {
String newStr = str.substring(0, i + 1);
prefix = new String[newStr.length() - 1];
suffix = new String[newStr.length() - 1];
for (int j = 0; j < newStr.length() - 1; j++) {
prefix[j] = newStr.substring(0, j + 1);
suffix[j] = newStr.substring(1 + j, newStr.length());
}
for (int j = 0; j < prefix.length; j++) {
if (prefix[j].equals(suffix[prefix.length - j - 1])) {
matchNum += prefix[j].length();
}
}
matchTable[i] = matchNum;
matchNum = 0;
}
}
}
return matchTable;
}
/**
* 查找字符串
* */
private String search(String str, String s, int[] partMatch) {
for (int i = 0; i < str.length(); i++) {
for (int j = 0; j < s.length(); j++) {
if (!str.substring(i, i + j + 1).equals(s.substring(0, j + 1))) {
if (j == 0) {
break;
} else {
int drift = j - partMatch[j - 1];
i = i + drift - 1;
break;
}
} else {
if (j == s.length() - 1) {
this.result = true;
this.index = i;
return null;
}
}
}
}
this.result = false;
this.index = -1;
return null;
}
public boolean isResult() {
return result;
}
public int getIndex() {
return index;
}
public String getMatchStr() {
return matchStr;
}
public void setMatchStr(String matchStr) {
this.matchStr = matchStr;
}
public String getTotalStr() {
return totalStr;
}
}
以下是调用方法
public static void main(String[] args) {
String str = "BBC ABCDAB ABCDABCDABDE";
String s1 = "ABCDABD";
String s2 = "BBA";
Kmp kmp = new Kmp(str, s1);
System.out.println(kmp.getIndex() + ":" + kmp.isResult());
kmp = new Kmp(str, s2);
System.out.println(kmp.getIndex() + ":" + kmp.isResult());
}
个人博客:www.katts.cn