import java.util.Scanner;
public class MainKMP {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
String str2 = sc.nextLine();
char[] strs = str1.toCharArray();
char[] strm = str2.toCharArray();
System.out.println(GetIndex(strs, strm));
}
public static int GetIndex(char[] strs, char[] strm) {
if (strm.length <= 0 || strs.length <= 0 || strm.length > strs.length)
return -1;
int[] nextArr = GetNextArray(strm);
int mi = 0;
int si = 0;
while (mi < strm.length && si < strs.length) {
if (strm[mi] == strs[si]) {
mi++;
si++;
}else if (mi > 0) {
mi = nextArr[mi];
} else {
si++;
}
}
return mi == strm.length ? si - mi : -1;
}
public static int[] GetNextArray(char[] str2) {
if (str2.length < 2) {
return new int[]{ -1 };
}
int[] nextArr = new int[str2.length];
nextArr[0] = -1;//第一个位置前面没有元素,将其定义为-1
nextArr[1] = 0;//第二个位置前面只有一个元素,匹配子串的定义是前缀子串不包括最后一个元素,后缀子串不包括第一个元素,因此前面匹配子串的长度为0
int pos = 2;//下一步进行比较的位置为第三个位置;
int cn = 0;//cn为上一个字符匹配前缀子串的下一个元素位置;
while (pos < str2.length) {
if (str2[pos] == str2[cn]) {
nextArr[pos++] = ++cn;
} else if (cn > 0) {
cn = nextArr[cn];
} else {
nextArr[pos++] = 0;
}
}
return nextArr;
}
}
KMP算法Java语言实现
最新推荐文章于 2024-07-25 12:55:52 发布