Guest User

Untitled

a guest
Oct 20th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. public class KMP {
  2.  
  3. private final String pattern;
  4. private final int[] next;
  5.  
  6. public KMP(String _pattern) {
  7. if (_pattern == null) {
  8. throw new IllegalArgumentException("pattern cannot be null");
  9. }
  10. else if (_pattern.isEmpty()) {
  11. throw new IllegalArgumentException("pattern cannot be empty");
  12. }
  13.  
  14. pattern = _pattern;
  15. next = computeNext(pattern);
  16. }
  17.  
  18. public String getPattern() {
  19. return pattern;
  20. }
  21.  
  22. public int firstOccurenceAt(String str) {
  23. return firstOccurenceAt(str, 0);
  24. }
  25.  
  26. public int firstOccurenceAt(String str, int initPos) {
  27. if (str == null
  28. || str.isEmpty()) {
  29. return -1;
  30. }
  31.  
  32. int iStr = initPos;
  33. int iPattern = 0;
  34. while (iStr < str.length() && iPattern < pattern.length()) {
  35. if (iPattern == -1
  36. || str.charAt(iStr) == pattern.charAt(iPattern)) {
  37. iStr++;
  38. iPattern++;
  39. }
  40. else {
  41. iPattern = next[iPattern];
  42. }
  43. }
  44.  
  45. if (iPattern == pattern.length()) {
  46. return iStr - pattern.length();
  47. }
  48. else {
  49. return -1;
  50. }
  51. }
  52.  
  53. private int[] computeNext(String pattern) {
  54. int patternLength = pattern.length();
  55. int[] next = new int[patternLength];
  56.  
  57. next[0] = -1;
  58. for (int i = 1; i < patternLength; i++) {
  59. // next[0..i-1] has been set properly
  60. // set next[i] properly
  61. char prevChar = pattern.charAt(i - 1);
  62. int potentialMatchPosition = next[i - 1];
  63.  
  64. while (potentialMatchPosition != -1
  65. && prevChar != pattern.charAt(potentialMatchPosition)) {
  66. potentialMatchPosition = next[potentialMatchPosition];
  67. }
  68.  
  69. next[i] = potentialMatchPosition + 1;
  70. }
  71. return next;
  72. }
  73.  
  74. public static void main(String[] args) {
  75. KMP kmp = new KMP("abcdabd");
  76. System.out.println(kmp.firstOccurenceAt("bbc abcdab abcdabcdabde"));
  77. }
  78.  
  79. }
Add Comment
Please, Sign In to add comment