Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int rabinKarp(String text, String pattern) {
- //Doing Double Hashing for cross-checking. Choose any 2 MOD and BASE which are primes.
- long MOD1 = (int) Math.pow(10,9)+7;
- long BASE1 = 101;
- long MOD2 = 2* (int) Math.pow(10,9) + 11;
- long BASE2 = 301;
- int n = text.length() , m = pattern.length(), i;
- if(n<m) return -1;
- //compute HashCode for the pattern
- long hashPattern1=0, hashPattern2=0;
- for(i = m-1; i >= 0; i--) {
- hashPattern1 = (hashPattern1 + pattern.charAt(i) * BASE1)% MOD1;
- hashPattern2 = (hashPattern2 + pattern.charAt(i) * BASE2)% MOD2;
- }
- long hashText1 =0 , hashText2 = 0;
- //compute hashCodes of the first M chars.
- for(i=0;i<m;i++) {
- hashText1 *= BASE1;
- hashText2 *= BASE2;
- hashText1 = (hashText1 + text.charAt(i))% MOD1;
- hashText2 = (hashText2 + text.charAt(i))% MOD2;
- }
- if(hashPattern1 == hashText1 && hashPattern2 == hashText2) return 0;
- for(i=m;i<n;i++) {
- hashText1 *= BASE1;
- hashText2 *= BASE2;
- hashText1 = (hashText1 + text.charAt(i))% MOD1;
- hashText2 = (hashText2 + text.charAt(i))% MOD2;
- if(hashPattern1 == hashText1 && hashPattern2 == hashText2) {
- // additionally verify that the text actually matches, can be done
- /*
- for(int j=0;j<m;j++)
- if(text.charAt(i+j) != pattern.charAt(j))
- break;
- if(j==m) return i;
- */
- return i;
- }
- }
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement