public class KMP {
public static void main(String[] args) {
String str = "ababcababa";
String partrn = "ababa";
System.out.println(KMPMatch(str, partrn));
}
static int KMPMatch(String str, String ptrn) {
int i = 0;
int j = 0;
int[] next = getNext(ptrn);
while (i < str.length()) {
if (j == -1 || str.charAt(i) == ptrn.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
if (j == ptrn.length()) {
return i - j;
}
}
return -1;
}
static int[] getNext(String str) {
int[] next = new int[20];
int i = 0;
int j = -1;
next[0] = -1;
while (i < str.length() - 1) {
if (j == -1 || str.charAt(j) == str.charAt(i)) {
j++;
i++;
} else {
j = next[j];
}
}
return next;
}
}
KMP算法
最新推荐文章于 2023-01-23 18:57:44 发布