public class KMP {
public void KMPMatch(String str,String pStr){
long beginTimes = System.currentTimeMillis();
int[] next = getNext(pStr);
int q = 0;
int count = 0;
for(int i = 0;i<str.length();i++){
while(q>0&&pStr.charAt(q)!=str.charAt(i)){
q = next[q-1];
}
if(pStr.charAt(q)==str.charAt(i)){
q++;
}
if(q==pStr.length()){
System.out.println("Pattern occurs with shift"+ ++count +"times");
q = next[q-1];
}
}
if(count==0){
System.out.println("There is no matcher!");
}
}
public int[] getNext(String pStr){
int[] next = new int[pStr.length()];
next[0]=0;
int k=0;
for(int i=1;i<pStr.length();i++){
while(k>0&&pStr.charAt(k)!=pStr.charAt(i)){
k = next[k-1];
}
if(pStr.charAt(k)==pStr.charAt(i)){
k++;
}
next[i]=k;
}
return next;
}
public static void main(String[] args){
KMP kmp;
kmp = new KMP();
kmp.KMPMatch("ababacabacbababababacabcbabababaca", "ababaca");
}
}
KMP算法(java版本)
最新推荐文章于 2022-08-10 15:31:52 发布