public class MethodKMP {
final static int MaxSize = 100;
//由模式串t求next[]数组算法
public static void GetNext(String t, int next[]) {
int j = 0, k = -1;
next[0] = -1;
while (j < t.length() - 1) {
if (k == -1 || t.charAt(j) == t.charAt(k))//k为-1或比较的字符相等时
{
j++;
k++;
next[j] = k;
} else k = next[k]; //k置为next[k]
}
}
//KMP算法
public static int KMP(String s, String t) {
int[] next = new int[MaxSize];
int i = 0, j = 0;
① //求next数组
while (i < s.length() && j < t.length()) {
if (j == -1 || s.charAt(i) == t.charAt(j)) {
i++;
② //i,j各增1
} else j = next[j]; //i不变,j回退
}
if (j >= t.length())
③ //返回起始序号
else
return -1; //返回-1
}
public static void main(String[] args) {
String s = "ababcabcacbab";
String t = "abcac";
int i = KMP(s, t);
if (i >= 0)
System.out.println("匹配成功 i=" + i);
else
System.out.println("匹配失败");
}
}