Skip to content

Commit 08899fa

Browse files
committed
Implement Rabin-Karp algorithm
1 parent 8be8b95 commit 08899fa

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.thealgorithms.strings;
2+
3+
public class RabinKarpAlgorithm {
4+
static final int d = 256;
5+
static final int q = 101;
6+
7+
//M = length of pattern
8+
// N = length 0f text
9+
static void robinKarpSearch(String pat,String txt,int M,int N){
10+
int h = 1;
11+
for (int i = 1; i <=M-1 ; i++) {
12+
h = (h*d)%q;
13+
}
14+
// Hash-value for pattern
15+
// Hash-value for text
16+
int p = 0,t = 0;
17+
for (int i = 0; i < M; i++) {
18+
p = (p*d+pat.charAt(i))%q;
19+
t = (t*d+txt.charAt(i))%q;
20+
}
21+
//Slide the pattern over text one by one
22+
for (int i = 0; i <=(N-M) ; i++) {
23+
//check the hash values of current window of
24+
//text and pattern. if hash-value match then only
25+
// check for characters one by one
26+
if(p==t){
27+
//checking for character one by one
28+
boolean flag = true;
29+
for (int j = 0; j < M; j++) {
30+
if(txt.charAt(i+j)!=pat.charAt(j)){
31+
flag = false;
32+
break;
33+
}
34+
}if (flag==true){
35+
System.out.println(i+" ");
36+
}
37+
}
38+
//Calculate hash-value for next window of text:
39+
// Remove leading digit. Add trailing digit
40+
if(i<N-M){
41+
t = ((d*(t-txt.charAt(i)*h))+txt.charAt(i+M))%q;
42+
}
43+
44+
//We might get negative value of t,
45+
// converting it to positive
46+
if(t<0){
47+
t = t+q;
48+
}
49+
}
50+
}
51+
52+
public static void main(String[] args) {
53+
String txt = "ABCCDDAEFG";
54+
String pat = "CDD";
55+
System.out.println("All index numbers where patter found: ");
56+
robinKarpSearch(pat,txt,pat.length(),txt.length());
57+
}
58+
}

0 commit comments

Comments
 (0)