请用java实现 kmp 算法
时间: 2024-05-02 14:22:04 浏览: 110
以下是Java实现的KMP算法代码:
```java
public class KMP {
public static int[] getNext(String pattern) {
int len = pattern.length();
int[] next = new int[len];
next[0] = -1;
int i = 0, j = -1;
while (i < len - 1) {
if (j == -1 || pattern.charAt(i) == pattern.charAt(j)) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
return next;
}
public static int kmpSearch(String text, String pattern) {
int[] next = getNext(pattern);
int i = 0, j = 0;
while (i < text.length() && j < pattern.length()) {
if (j == -1 || text.charAt(i) == pattern.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == pattern.length())
return i - j;
else
return -1;
}
public static void main(String[] args) {
String text = "ABCABCABCABCABCABD";
String pattern = "ABCABD";
int index = kmpSearch(text, pattern);
if (index != -1) {
System.out.println("Pattern found at index " + index);
} else {
System.out.println("Pattern not found");
}
}
}
```
阅读全文