主题思想: 写一个用于字符串匹配的BoyerMoore 算法,KMP 算法,我现在不会,但是这个算法,好写,且容易理解。我来徒手写下。
public class BoyerMoore{
private String pat;
private int[] right;
public BoyerMoore(String pat){
this.pat=pat;
int M=pat.length();
int R=256;
right=new int[R];
for(int c=0;c<R;c++)
right[c]=-1;
for(int j=0;j<M;j++)
right[pat.charAt(j)]=j;
}
public int search(String txt){
int N=txt.length();
int M=pat.length();
int skip;
for(int i=0;i<N-M;i+=skip){
skip=0;
for(int j=M-1;j>=0;j--)
if(txt.charAt(i+j)!=pat.charAt(j)){
skip=j-right[txt.charAt(i+j)]
if(skip<1) skip=1;
break;
}
if(skip==0)return i;
}
return N;
}
}