Rabin Karp Rolling Hash Pattern Match (Java)
Find all occurrences of a pattern in Java text using Rabin Karp with a rolling hash for O(n+m) average time.
Code
import java.util.*;
public class RabinKarp {
public static List<Integer> search(String text, String pattern) {
int base = 256, mod = 101, n = text.length(), m = pattern.length();
if (m == 0 || m > n) return List.of();
int patH = 0, txtH = 0, h = 1;
for (int i = 0; i < m - 1; i++) h = (h * base) % mod;
for (int i = 0; i < m; i++) { patH = (patH * base + pattern.charAt(i)) % mod; txtH = (txtH * base + text.charAt(i)) % mod; }
List<Integer> result = new ArrayList<>();
for (int i = 0; i <= n - m; i++) { if (patH == txtH && text.substring(i, i + m).equals(pattern)) result.add(i); if (i < n - m) { txtH = (base * (txtH - text.charAt(i) * h) + text.charAt(i + m)) % mod; if (txtH < 0) txtH += mod; } }
return result;
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.