本博文用Java实现了KMP模式匹配算法
附上大神超详细解释:KMP算法详细解释
/*
* KMP算法
*
* */
private int[] getNextVal(IString T){
int [] nextVal = new int[T.length()];
int j = 0;
int k = -1;
nextVal[0] = -1;
while (j<T.length()-1){
if (k == -1||T.charAt(j) == T.charAt(k)){
j++;
k++;
if (T.charAt(j) != T.charAt(k))
nextVal[j] = k;
else
nextVal[j] = nextVal[k];
}else
k = nextVal[k];
}
return nextVal;
}
public int index_KPM(IString T,int start){
int [] next = getNextVal(T);//计算模式串next[]函数值
int i = start;//主串指针
int j = 0;//模式串指针
//对两串从左到右逐个比较字符
while (i<this.length()&& j<T.length()){
if (j == -1||this.charAt(i)==T.charAt(j)){
i++;
j++;
}else {
j = next[j];//模式串右移
}
}
if (j<T.length()){
return -1;
}else {
return (i-T.length());//匹配成功
}
}