学习了下KMP算法 感觉挺难理解 看了好几篇博客总算是搞明白了,为此记录一下,用java 实现一下。
public static void main(String args[]) {
System.out.println(kmpSearch("AADCBDFEHIJKLBBCDD","HIJK"));
}
/**
*
* @param s 主串
* @param p 模式串
* @return
*/
public static int kmpSearch(String s, String p) {
if (s == null || p == null) {
return -1;
}
char[] sCharArray = s.toCharArray();
char[] pCharArray = p.toCharArray();
int[] next = getNext(pCharArray);
int i = 0, j = 0;
while (i < sCharArray.length && j < pCharArray.length) {
if (j==-1 ||sCharArray[i] == pCharArray[j]) {
i++;
j++;
} else
j = next[j];
}
if (j == pCharArray.length) {
return i - j;
} else
return -1;
}
/**
*
* @param p
* @return
*/
public static int[] getNext(char[] p) {
int[] next = new int[p.length];
next[0] = -1;
next[1] = 0;
int k;
for (int j = 2; j < p.length; j++) {
k = next[j - 1];
while (k != -1) {
if (p[j - 1] == p[k]) {
next[j] = k + 1;
} else {
k = next[k];
}
}
next[j] = 0;
}
return next;
}