java实现kmp算法
时间: 2023-02-19 18:39:05 浏览: 122
我不太清楚如何用Java实现KMP算法,但是我可以给你一些参考资料:https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/
相关问题
java实现KMP算法
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。
java 实现 kmp算法
以下是Java的KMP算法实现示例:
```java
public class KMPAlgorithm {
public static int kmpSearch(String text, String pattern) {
int[] next = getNextArray(pattern);
int i = 0; // text中的指针
int j = 0; // pattern中的指针
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; // 匹配成功,返回在text中的起始位置
} else {
return -1; // 匹配失败
}
}
private static int[] getNextArray(String pattern) {
int[] next = new int[pattern.length()];
next[0] = -1;
int i = 0;
int j = -1;
while (i < pattern.length() - 1) {
if (j == -1 || pattern.charAt(i) == pattern.charAt(j)) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
return next;
}
public static void main(String[] args) {
String text = "ABABABCDABABCABAB";
String pattern = "ABABCABAB";
int index = kmpSearch(text, pattern);
if (index != -1) {
System.out.println("Pattern found at index " + index);
} else {
System.out.println("Pattern not found");
}
}
}
```
在上述示例中,`kmpSearch()`方法用于执行KMP算法的搜索过程,`getNextArray()`方法用于生成模式串的next数组。在`main()`方法中,我们演示了如何使用KMP算法在文本串中查找模式串的位置。