Below is the Rabin Karp implementation. I am not so sure about it, and there is no where that I can check whether this code really works or not. It will most helpful for extra set of eyes if whether this gives correct output or not. The code finds the substring (in code it is, pattern) from the string given (in code it is, text). If the substring is found it will return true, otherwise false.
public class RabinKarpSubstring {
// Check if text contains pattern.
public boolean isSubstring (String pattern, String text) {
if (pattern.length() > text.length()) return false;
int prime = 31;
int MOD = 1000000009;
long hashPattern = 0;
long[] primePower = new long[text.length()];
long[] hashText = new long[text.length() + 1];
primePower[0] = 1;
for (int i = 1; i < text.length(); i++) {
primePower[i] = (primePower[i - 1] * prime) % MOD;
}
for (int i = 0; i < text.length(); i++) {
hashText[i + 1] = (hashText[i] + ((text.charAt(i) - 'a' + 1) * primePower[i])) % MOD;
}
for (int i = 0; i < pattern.length(); i++) {
hashPattern = (hashPattern + ((pattern.charAt(i) - 'a' + 1) * primePower[i])) % MOD;
}
for (int i = 0; i < (text.length() - pattern.length() + 1); i++) {
long currHash = (hashText[i + pattern.length()] + MOD - hashText[i]) % MOD;
if (currHash == (hashPattern * primePower[i] % MOD)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(new RabinKarpSubstring().isSubstring("aab", "aaaab"));
}
}
Please do share if anymore information is to added. Thank you.