Advertisement
Guest User

Untitled

a guest
Oct 20th, 2013
404
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. public static int rabinKarp(String text, String pattern) {
  2. //Doing Double Hashing for cross-checking. Choose any 2 MOD and BASE which are primes.
  3. long MOD1 = (int) Math.pow(10,9)+7;
  4. long BASE1 = 101;
  5. long MOD2 = 2* (int) Math.pow(10,9) + 11;
  6. long BASE2 = 301;
  7. int n = text.length() , m = pattern.length(), i;
  8. if(n<m) return -1;
  9. //compute HashCode for the pattern
  10. long hashPattern1=0, hashPattern2=0;
  11. for(i = m-1; i >= 0; i--) {
  12. hashPattern1 = (hashPattern1 + pattern.charAt(i) * BASE1)% MOD1;
  13. hashPattern2 = (hashPattern2 + pattern.charAt(i) * BASE2)% MOD2;
  14. }
  15. long hashText1 =0 , hashText2 = 0;
  16. //compute hashCodes of the first M chars.
  17. for(i=0;i<m;i++) {
  18. hashText1 *= BASE1;
  19. hashText2 *= BASE2;
  20. hashText1 = (hashText1 + text.charAt(i))% MOD1;
  21. hashText2 = (hashText2 + text.charAt(i))% MOD2;
  22. }
  23. if(hashPattern1 == hashText1 && hashPattern2 == hashText2) return 0;
  24. for(i=m;i<n;i++) {
  25. hashText1 *= BASE1;
  26. hashText2 *= BASE2;
  27. hashText1 = (hashText1 + text.charAt(i))% MOD1;
  28. hashText2 = (hashText2 + text.charAt(i))% MOD2;
  29. if(hashPattern1 == hashText1 && hashPattern2 == hashText2) {
  30. // additionally verify that the text actually matches, can be done
  31. /*
  32. for(int j=0;j<m;j++)
  33. if(text.charAt(i+j) != pattern.charAt(j))
  34. break;
  35. if(j==m) return i;
  36. */
  37. return i;
  38. }
  39. }
  40. return -1;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement