The key to Rabin Karp algorithm is to compute the hash effectively and quickly. This is done by dynamic programming, which is current substring hash value is computed based on the previous one.
Here is the Rabin Karp algorithm to solve an online algorithm for palindrome checking.
Thanks to Peng Li for bringing up this problem. Here is the link to his page on this: http://allenlipeng47.com/PersonalPage/index/view/157/nkey
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
your code has no difference with the on in g4g(http://www.geeksforgeeks.org/online-algorithm-for-checking-palindrome-in-a-stream/).
ReplyDeleteMy code adds a function for queue. It can help queue be able to compute hashcode in O(1) time when enQueue or deQueue happens. You remember we wrote the code to monitor max/min value in queue? I think this can make queue much powerful.
this code is slightly different that in stead of compute first/second half, it compute forward/backward.
Deletedo we need deQueue op?