Skip to content

Commit 26828a7

Browse files
committed
add: initial implementation of Rabin-Karp algorithm for string matching
1 parent 633b9d4 commit 26828a7

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package com.thealgorithms.strings;
2+
import java.util.*;
3+
4+
public class PatternSearchUsingRabinKarpAlgo {
5+
6+
// I'm using Rabin-Karp algorithm that uses hashing to find pattern strings in a text.
7+
public static List<String> search(String text, String pattern) {
8+
List<String> result = new ArrayList<>();
9+
int m = pattern.length();
10+
int n = text.length();
11+
int prime = 101; // A prime number to mod hash values
12+
13+
int patternHash = 0; // Hash value for pattern
14+
int textHash = 0; // Hash value for text window
15+
int h = 1;
16+
17+
// The value of h would be "pow(d, m-1) % prime"
18+
for (int i = 0; i < m - 1; i++) {
19+
h = (h * 256) % prime;
20+
}
21+
22+
// Calculating the hash value of pattern and first window of text
23+
for (int i = 0; i < m; i++) {
24+
patternHash = (256 * patternHash + pattern.charAt(i)) % prime;
25+
textHash = (256 * textHash + text.charAt(i)) % prime;
26+
}
27+
28+
// Iterating on pattern by single char again and again..
29+
for (int i = 0; i <= n - m; i++) {
30+
31+
if (patternHash == textHash) {
32+
// If the hash values match, then only checking for next char's
33+
int j;
34+
for (j = 0; j < m; j++) {
35+
if (text.charAt(i + j) != pattern.charAt(j)) {
36+
break;
37+
}
38+
}
39+
40+
// If patternHash == textHash and pattern[0...m-1] == text[i...i+m-1]
41+
if (j == m) {
42+
result.add("Start: " + i + ", End: " + (i + m - 1) + ", Substring: " + text.substring(i, i + m));
43+
}
44+
}
45+
46+
// Calculating hash value for next window of text: Remove leading digit, add trailing digit
47+
if (i < n - m) {
48+
textHash = (256 * (textHash - text.charAt(i) * h) + text.charAt(i + m)) % prime;
49+
50+
// We might get negative value of textHash,so converting it to positive
51+
if (textHash < 0) {
52+
textHash = (textHash + prime);
53+
}
54+
}
55+
}
56+
57+
return result;
58+
}
59+
60+
public static void main(String[] args) {
61+
62+
Scanner in = new Scanner(System.in);
63+
System.out.print("Enter the string: ");
64+
String text = in.next();
65+
// String text = "ABCCDDAEFG"; test
66+
67+
System.out.print("Enter the searching string: ");
68+
String pattern = in.next();
69+
// String pattern = "CDD"; testt
70+
71+
List<String> result = search(text.toLowerCase(), pattern.toLowerCase());
72+
73+
if (result.isEmpty()) {
74+
System.out.println("Pattern not found in the given text.");
75+
} else {
76+
System.out.println("Pattern found: " + result);
77+
}
78+
}
79+
}

0 commit comments

Comments
 (0)