用java写一个kmp
时间: 2024-05-25 19:16:03 浏览: 97
Java实现KMP算法
public class KMP {
public static int[] computeLPS(String pattern) {
int[] lps = new int[pattern.length()];
int i = 1, j = 0;
while (i < pattern.length()) {
if (pattern.charAt(i) == pattern.charAt(j)) {
lps[i++] = ++j;
} else {
if (j != 0) {
j = lps[j - 1];
} else {
lps[i++] = 0;
}
}
}
return lps;
}
public static int findPattern(String text, String pattern) {
int[] lps = computeLPS(pattern);
int i = 0, j = 0;
while (i < text.length() && j < pattern.length()) {
if (text.charAt(i) == pattern.charAt(j)) {
i++;
j++;
} else {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
if (j == pattern.length()) {
return i - j;
} else {
return -1;
}
}
public static void main(String[] args) {
String text = "ABABDABACDABABCABAB";
String pattern = "ABABCABAB";
int index = findPattern(text, pattern);
if (index != -1) {
System.out.println("Pattern found at index " + index);
} else {
System.out.println("Pattern not found in the text.");
}
}
}
阅读全文