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.