Skip to content

Instantly share code, notes, and snippets.

@junminstorage
Created May 22, 2015 19:37
Show Gist options
  • Save junminstorage/c540070ad36f6ecc322b to your computer and use it in GitHub Desktop.
Save junminstorage/c540070ad36f6ecc322b to your computer and use it in GitHub Desktop.
Rabin Karp Algorithm - string rolling hash
package org.blueocean;
public class RabinKarpString {
static final int prime = 101;
static final int base = 103;
public static void rabinKarp(String s){
assert(s!=null && !s.isEmpty());
long leftHash = s.charAt(0);
long rightHash = s.charAt(0);
System.out.println("Yes");
int h = 1;
for(int i = 1; i < s.length(); i++){
h = (h*prime)%base;
leftHash = (leftHash*prime + s.charAt(i))%base;
rightHash = ( (long) (s.charAt(i)*h + rightHash))%base;
if(leftHash == rightHash){
isPali(s, i);
}else
System.out.println("No");
}
}
public static void isPali(String s, int i){
for(int l=0,r=i; l<=r; l++, r--){
if(s.charAt(l) != s.charAt(r)){
System.out.println("No");
}
}
System.out.println("Yes");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment