写的很菜,理解的不是很深刻!贴出来共勉吧!!
先来几个大神的连接
大神一
public class Main {
private static String par;
private static String ori;
public static void main(String[] args) {
ori = "BBC ABCDABD ABCD E";// 原串
par = "ABCDABD";// 模式串
char[] s = ori.toCharArray();
char[] t = par.toCharArray();
System.out.println(KMP_Index(s, t));
}
private static int KMP_Index(char[] s, char[] t) {
// TODO Auto-generated method stub
int[] next = next(t);
int i = 0;
int j = 0;
while (i <= s.length - 1 && j <= t.length - 1) {
if (j == -1 || s[i] == t[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j < t.length) {
return -1;
} else {
return i - t.length;
}
}
private static int[] next(char[] t) {//获取模式串的next数组
// TODO Auto-generated method stub
int next[] = new int[t.length];
next[0] = -1;
int i = 0;
int j = -1;
while (i < t.length - 1) {
if (j == -1 || t[i] == t[j]) {
i++;
j++;
if (t[i] != t[j]) {
next[i] = j;
} else {
next[i] = next[j];
}
} else {
j = next[j];
}
}
return next;
}
}
688

被折叠的 条评论
为什么被折叠?



