关于RK算法存在的问题

我最近在使用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"));

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值