0
点赞
收藏
分享

微信扫一扫

Java实现KMP算法

直接上算法实现及测试代码

public class KMP {

public static int getIndexOf(String s1, String s2) {
if (s1 == null || s2 == null || s2.isEmpty() || s1.length() < s2.length()) {
return -1;
}
char[] str1 = s1.toCharArray();
char[] str2 = s2.toCharArray();
int[] next = getNextArray(str2);
int index1 = 0;
int index2 = 0;
while (index1 < str1.length && index2 < str2.length) {
if (str1[index1] == str2[index2]) {
index1++;
index2++;
} else if (index2 == 0) {
index1++;
} else {
index2 = next[index2];
}
}
return index2 == str2.length ? index1 - index2 : -1;
}

public static int[] getNextArray(char[] str2) {
if (str2.length == 1) {
return new int[0];
}
int[] next = new int[str2.length];
// next[0] = -1;
// next[1] = 0;
int index = 2;
int cn = 0;
while (index < str2.length) {
if (str2[index - 1] == str2[cn]) {
next[index++] = ++cn;
} else if (cn > 0) {
cn = next[cn];
} else {
next[index++] = 0;
}
}
return next;
}

// for test
public static String getRandomString(int possibilities, int size) {
char[] ans = new char[(int) (Math.random() * size) + 1];
for (int i = 0; i < ans.length; i++) {
ans[i] = (char) ((int) (Math.random() * possibilities) + 'a');
}
return String.valueOf(ans);
}

public static void main(String[] args) {
int possibilities = 5;
int strSize = 20;
int matchSize = 5;
int testTimes = 5000000;
System.out.println("test begin");
for (int i = 0; i < testTimes; i++) {
String str = getRandomString(possibilities, strSize);
String match = getRandomString(possibilities, matchSize);
if (getIndexOf(str, match) != str.indexOf(match)) {
System.out.println("Oops!");
}
}
System.out.println("test finish");
}
}


举报

相关推荐

KMP 算法

kmp 算法

【算法】KMP算法

VBA实现KMP和LCS算法

0 条评论