public class KMP {
public static void main(String[] args) {
String s1 = "xiatiannihao";
String s2 = "a";
System.out.println(getStringIndex(s1,s2));
}
public static int getStringIndex(String str1, String str2){
if(str1 == null || str2==null || str1.length()<str2.length()){
return 0;
}
char[] chs1 = str1.toCharArray();
char[] chs2 = str2.toCharArray();
int s1 = 0;
int s2 = 0;
int[] next = getNextArray(chs2); // 求next数组
while(s1<str1.length() && s2<str2.length()){
if(chs1[s1] == chs2[s2]){
s1++;
s2++;
}else if(next[s2] != -1){
s2 = next[s2];
}else{
s1++; // 如果str1同 str2的第一个字符都不相等,那么str1就向后移一个位置比较
}
}
return s2 == str2.length() ? s1-s2 : -1;
}
public static int[] getNextArray(char[] str2){
if(str2.length == 1){
return new int[]{-1};
}
int[] next = new int[str2.length];
next[0] = -1; // 人为固定
next[1] = 0; // 人为固定
int i = 2; // 从下标2开始
int cn = 0; // 一开始和下标0比较
while(i<str2.length){
if(str2[i-1] == str2[cn]){
next[i++] = ++cn;
}else if(cn > 0){
cn = next[cn]; // 从已有的next数组获取信息
}else{
next[i++] = 0;
}
}
return next;
}
}
kmp算法很经典。影响了后续很多的算法,这些算法借鉴了kmp算法的思想。