最终还是选择用java而不是python,其实没有什么难不难,当初学个乘法口诀也是很难,人总是要不断进取的。
希望在美国找工作顺利
一、基础知识
二、code
package basic_class_02;
public class Code_01_KMP {
public static int getIndexOf(String s, String m) {
if (s == null || m == null || m.length() < 1 || s.length() < m.length()) {
return -1;
}
char[] ss = s.toCharArray();
char[] ms = m.toCharArray();
int si = 0;
int mi = 0;
int[] next = getNextArray(ms);
while (si < ss.length && mi < ms.length) {
if (ss[si] == ms[mi]) {
si++;
mi++;
} else if (next[mi] == -1) {
si++;//str2已经到了第一个了还是匹配不上,开头不行,你str1就++吧
} else {
mi = next[mi];//就是说str2还可以跳
}
}
return mi == ms.length ? si - mi : -1;
}
public static int[] getNextArray(char[] ms) {
if (ms.length == 1) {
return new int[] { -1 };
}
int[] next = new int[ms.length];
next[0] = -1;
next[1] = 0;
int pos = 2;//后面减一了,长度 位置
int cn = 0;
while (pos < next.length) {
if (ms[pos - 1] == ms[cn]) {
//表示长度+1
next[pos++] = ++cn; //next k=k
//cn跳到的位置跟前一个不等,两种情况 可以往前跳 或者到了最左边了
} else if (cn > 0) {//我还可以往前跳
cn = next[cn];//next数组的值就是我要跳的位置
} else {
//跳到最左了,当前位置的最长前缀和最长后缀是0
next[pos++] = 0;
}
}
return next;
}
public static void main(String[] args) {
String str = "abcabcababaccc";
String match = "ababa";
System.out.println(getIndexOf(str, match));
}
}