package 字符串;
public class KMP {
public static int[] getNextarr(char[] str2) {
if(str2.length < 2) {
return new int[]{ -1 };
}
int[] next = new int[str2.length];
next[0] = -1;
next[1] = 0;
int cn = 0; // cn指的是跳到的位置也就是字符串中i-1位置字符最大前缀+1的位置
int i= 2; // str2中各个字符的指针
while(i < str2.length) {
if(str2[i - 1] == str2[cn]) {
next[i++] = ++cn;
}else if(cn > 0){
cn = next[cn]; // 往后跳一个
}else {
next[i++] = 0;
}
}
return next;
}
public static int getIndexof(String s1, String s2) {
if(s2 == null) {
return -1;
}
char[] str1 = s1.toCharArray();
char[] str2 = s2.toCharArray();
int[] next = getNextarr(str2);
int i = 0;
int j = 0;
while(i < str1.length && j < str2.length) {
if(str1[i] == str2[j]) {
i++;
j++;
}else if(next[j] == -1) {
i++;
}else {
j = next[j];
}
}
return j == str2.length ? i - j : -1; // 如果j!=str2.length就说明str1中不存在str2这个子序列
}
public static void main(String[] args) {
String s1 = "abcabaaaa";
String s2 = "a";
int res = getIndexof(s1, s2);
// int res1 = s1.indexOf(s2);
System.out.println(res);
}
}
2019-05-23KMP
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 1.连续3周时间无间断过,每天清晨问自己三个问题:第一个问题:对我来说什么是最有价值的事情?第二个问题:要做什么事...
- 一个人可以做很多事 一个人买饭,吃饭,散步, 一个人上课,看书,复习, 一个人唱歌,跑步,逛街, 可你终究是一个人...