Advertisement
Guest User

Untitled

a guest
Apr 17th, 2014
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. @Override
  2. public List<Integer> rabinKarp(String needle, String haystack) {
  3. ArrayList<Integer> toReturn = new ArrayList<Integer>();
  4. int base = BASE;
  5. int power = pow(base, needle.length() - 1);
  6. int hash = generateHash(needle);
  7. int prev = generateHash(needle);
  8. if (prev == hash && check(needle, haystack, 0)) {
  9. return null;
  10. }
  11. for (int i = 1; i < haystack.length() - needle.length() + 1; i++) {
  12. prev = updateHash(prev, needle.length(), haystack.charAt(i - 1), haystack.charAt(i + needle.length() - 1));
  13. if (prev == hash && check(needle, haystack, i)) {
  14. toReturn.add(i);
  15. return toReturn;
  16. }
  17. }
  18. toReturn.add(-1);
  19. return toReturn;
  20. }
  21.  
  22. private boolean check(String needle, String haystack, int start) {
  23. if (start + needle.length() - 1 >= haystack.length()) {
  24. return false;
  25. }
  26. for (int i = 0; i < needle.length(); i++) {
  27. if (needle.charAt(i) != haystack.charAt(i + start)) {
  28. return false;
  29. }
  30. }
  31. return true;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement