public class KMP{
public int kmp_pattern(String T,String P){
if(T == null || P == null || T.length() == 0 || P.length() == 0 || T.length() < P.length())
return -1;
int [] next = getNext(P);//获取匹配字符串的next数组
int i = 0,j = 0;
//KMP算法
while(i < T.length() && j < P.length()){
if(T.charAt(i) == P.charAt(j)){
i++;
j++;
}else{
if(j == 0){
i++;
}else{
j = next[j];
}
}
}
if(j == P.length()){
return i - j;
}else{
return -1;
}
}
/**
*获取next数组
*/
public int [] getNext(String s){
if(s == null || s.length() == 0) return null;
int [] next = new int [s.length()];
next[0] = -1;
for(int i = 1;i < s.length();i++){
for(int j = i-1;j > 0;j--){
if(s.substring(0,j).equals(s.substring(i-j,i))){
next[i] = j;
break;
}
}
}
return next;
}
}
KMP算法
最新推荐文章于 2024-11-16 09:45:51 发布