用Java实现kmp算法
时间: 2023-03-07 18:31:52 浏览: 149
Java实现KMP算法的详细步骤如下:
1、初始化next数组:next[1] = -1,next[i] = 0(2≤i≤m)
2、从第i个字符开始,计算next[i]
3、当s[i] == s[k],则next[i+1] = k+1;
4、当s[i] != s[k],则查找next[k],让k = next[k],重复第3步
5、当k = -1,则让next[i+1] = 0;
6、输出next数组,完成KMP算法的实现。
相关问题
请用java实现 kmp 算法
以下是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");
}
}
}
```
Java实现kmp算法
public class KMP {
private int[] next;
public int[] getNext(String pattern) {
int length = pattern.length();
int[] next = new int[length];
next[0] = -1;
int i = 0;
int j = -1;
while (i < length - 1) {
if (j == -1 || pattern.charAt(i) == pattern.charAt(j)) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
return next;
}
public int kmp(String str, String pattern) {
int[] next = getNext(pattern);
int i = 0;
int j = 0;
int sLength = str.length();
int pLength = pattern.length();
while (i < sLength && j < pLength) {
if (j == -1 || str.charAt(i) == pattern.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == pLength) {
return i - j;
} else {
return -1;
}
}
}
阅读全文