kmp演算法實現
阿新 • • 發佈:2021-01-01
kmp核心就是求next陣列,而求next陣列核心就是記住,next[i]儲存的是模式串當前索引不匹配是下一個應該比較的索引
public class KMP {
//p模式串
public static int match(String p,String s){
if(s.length()<p.length())
return -1;
int[] next = new int[p.length()];
next[0] = -1;
int j=-1;
int i=0;
while(i<p.length()- 1){
if(j==-1||p.charAt(i)==p.charAt(j)){
j++;
i++;
next[i] = j;
//next優化
while(next[i]!=-1&&p.charAt(next[i])==p.charAt(i)){
next[i] = next[next[i]];
}
}else {
j = next[j];
}
}
i=0;
j=0;
while((s.length()-i>=p.length()-j)){
if(j==-1||s.charAt(i)==p.charAt(j)){
i++;
j++;
if(j==p.length()-1){
return i-p.length()+1;
}
}else {
j=next[j];
}
}
return -1;
}
}