Rabin Karp Matching: String Matching

Rabin Karp matching:

这里写图片描述
这里写图片描述


Pseudo code:

这里写图片描述


Java code:

/**
 * Created with IntelliJ IDEA.
 * User: 1O1O
 * Date: 2015-03-31
 * Time: 17:58 PM
 * :)~
 * RABIN-KARP-MATCH:STRING-MATCH
 */
public class Main {
    public static void RABIN_KARP_MATCHER(String Text, String Pattern, int d, int q){
        int n = Text.length();
        int m = Pattern.length();
        char[] textToChar = Text.toCharArray();
        char[] patternToChar = Pattern.toCharArray();
        int h = (int)Math.pow(d,m-1) % q;
        int p = 0;
        int[] t = new int[n-m+1];
        t[0] = 0;

        for(int i=1; i<=m; i++){
            p = (d*p+Character.digit(patternToChar[i-1],10))%q;
            t[0] = (d*t[0]+Character.digit(textToChar[i-1],10))%q;
        }

        for(int s=0; s<=n-m; s++){
            if(p==t[s]){
                int count = 0;
                for(int j=0; j<m; j++){
                    if(patternToChar[j]==textToChar[s+j])
                        count++;
                    else
                        break;
                }
                if(count==m){
                    System.out.println("Pattern occurs with shift: "+(s+1));
                }
            }
            if(s<n-m){
                int temp = t[s]-Character.digit(textToChar[s], 10)*h;
                temp = (temp<0)?temp+13:temp;
                t[s+1] = (d*temp+Character.digit(textToChar[s+m], 10))%q;
            }
        }
    }

    public static void main(String[] args) {
        String Text = "2359023141526739921";
        String Pattern = "31415";
        RABIN_KARP_MATCHER(Text, Pattern, 10, 13);
    }
}

Output:

Pattern occurs with shift: 7

Reference:

From: 《INTRODUCTION TO ALGORITHMS》THIRD EDITION. 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值