Advertisement
Pisitmidn

Untitled

Mar 22nd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1.         public static int findKMP(char[ ] text, char[ ] pattern) {
  2.         int n = text.length;
  3.         int m = pattern.length;
  4.         if (m == 0) return 0; // trivial search for empty string
  5.         int[ ] fail = computeFailKMP(pattern); // computed by private utility
  6.         int j = 0; // index into text
  7.         int k = 0; // index into pattern
  8.         while (j < n) {
  9.             if (text[j] == pattern[k]) { // pattern[0..k] matched thus far
  10.                 if (k == m - 1) return j - m + 1; // match is complete
  11.                 j++; // otherwise, try to extend match
  12.                 k++;
  13.             } else if (k > 0)
  14.                 k = fail[k-1]; // reuse suffix of P[0..k-1]
  15.             else
  16.                 j++;
  17.         }
  18.         return -1; // reached end without match
  19.     }
  20.  
  21.     private static int[ ] computeFailKMP(char[ ] pattern) {
  22.         int m = pattern.length;
  23.         int[ ] fail = new int[m]; // by default, all overlaps are zero
  24.         int j = 1;
  25.         int k = 0;
  26.         while (j < m) { // compute fail[j] during this pass, if nonzero
  27.             if (pattern[j] == pattern[k]) { // k + 1 characters match thus far
  28.                 fail[j] = k + 1;
  29.                 j++;
  30.                 k++;
  31.             } else if (k > 0) // k follows a matching prefix
  32.                 k = fail[k-1];
  33.             else // no match found starting at j
  34.                 j++;
  35.         }
  36.         return fail;
  37.     }
  38.  
  39.     public static int findBrute(char[ ] text, char[ ] pattern) {
  40.         int n = text.length;
  41.         int m = pattern.length;
  42.         for (int i=0; i <= n - m; i++) { // try every starting index within text
  43.             int k = 0; // k is index into pattern
  44.             while (k < m && text[i+k] == pattern[k]) // kth character of pattern matches
  45.                 k++;
  46.             if (k == m) // if we reach the end of the pattern,
  47.                 return i; // substring text[i..i+m-1] is a match
  48.         }
  49.         return -1; // search failed
  50.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement