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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 1.連續(xù)3周時間無間斷過,每天清晨問自己三個問題:第一個問題:對我來說什么是最有價值的事情?第二個問題:要做什么事...
- 一個人可以做很多事 一個人買飯,吃飯,散步, 一個人上課,看書,復(fù)習(xí), 一個人唱歌,跑步,逛街, 可你終究是一個人...