java实现KMP算法
时间: 2023-07-26 18:33:15 浏览: 118
KMP算法是一种字符串匹配算法,可以在O(m+n)的时间复杂度内在一个文本串中查找一个模式串是否出现。以下是Java实现KMP算法的代码:
```java
public class KMP {
public static int[] getNext(String p) {
int[] next = new int[p.length()];
int j = 0, k = -1;
next[0] = -1;
while (j < p.length() - 1) {
if (k == -1 || p.charAt(j) == p.charAt(k)) {
j++;
k++;
if (p.charAt(j) != p.charAt(k)) {
next[j] = k;
} else {
next[j] = next[k];
}
} else {
k = next[k];
}
}
return next;
}
public static int kmp(String s, String p) {
int[] next = getNext(p);
int i = 0, j = 0;
while (i < s.length() && j < p.length()) {
if (j == -1 || s.charAt(i) == p.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == p.length()) {
return i - j;
} else {
return -1;
}
}
}
```
其中,getNext方法用于计算模式串p的next数组,kmp方法用于在文本串s中查找模式串p。
阅读全文
相关推荐














