我最近在使用RK算法处理字符串匹配的时候,发现对于部分长字符串,存在无法匹配的情况,不知道是不是算法本身存在漏洞,但是因为自己能力有限,无法得出这个算法的漏洞在哪里,所以请各位帮帮忙!
下面是我用java实现的RK算法,输入两个字符串,输出匹配字符串在原字符串的索引位置,没有匹配输出-1
已经经过测试,可以正常使用
public int RK(String haystack,String needle){
int L = haystack.length();
int N = needle.length();
if(L < N){
return -1;
}
long a = 26;
//防止溢出
long module = (long) Math.pow(2,31);
long h = 0;
long ref_h = 0;
for(int i =0;i<N;i++){
h = (a*h + charToInt(haystack.charAt(i))) % module;
ref_h = (a*ref_h + charToInt(needle.charAt(i))) % module;
}
if(h == ref_h){
return 0;
}
long aN = 1;
for(int i =1;i<=N;i++){
aN = (aN*a) % module;
}
for(int start =1;start < L-N+1;start++){
h = (h *a +charToInt(haystack.charAt(start+N-1)) - aN * (charToInt(haystack.charAt(start-1)))) % module;
if(h == ref_h){
return start;
}
}
return -1;
}
但是,当我输入字符串odgoodgoodbestword
匹配字符串是odgoodgoodbestword
的时候,却无法得出匹配的结果
public static void main(String[] args) {
Solution s = new Solution();
//输出-1,理论输出1
System.out.println(s.RK("odgoodgoodbestword","dgoodgoodbestword"));
//输出1
System.out.println(s.RK("qdgoodgoodbestword","dgoodgoodbestword"));
}