mjain

KMP algo for pattern search

Jul 24th, 2019
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.22 KB | None | 0 0
  1. public class KMPAlgo {
  2.  
  3.     public static void main(String[] args) {
  4.         String txt = "ABABDABACDABABCABAB";
  5.         String pattern = "ABABCABAB";
  6.         int[] lps = computeLPS(pattern);
  7.         countOccurance(txt, pattern, lps);
  8.     }
  9.  
  10.     public static void countOccurance(String txt, String pat, int[] lps) {
  11.         if (pat == null || pat.isEmpty() || txt == null || txt.isEmpty()) {
  12.             return;
  13.         }
  14.         int M = pat.length();
  15.         int N = txt.length();
  16.  
  17.         int indexForPattern = 0;
  18.  
  19.         int positionForTExt = 0;
  20.         while (positionForTExt < N) {
  21.             if (pat.charAt(indexForPattern) == txt.charAt(positionForTExt)) {
  22.                 indexForPattern++;
  23.                 positionForTExt++;
  24.             }
  25.             if (indexForPattern == M) {
  26.                 System.out.println("Found pattern " + "at index " + (positionForTExt - indexForPattern));
  27.                 indexForPattern = lps[indexForPattern - 1];
  28.             }
  29.  
  30.             // mismatch after j matches
  31.             else if (positionForTExt < N && pat.charAt(indexForPattern) != txt.charAt(positionForTExt)) {
  32.                 if (indexForPattern != 0) {
  33.                     indexForPattern = lps[indexForPattern - 1];
  34.                 } else {
  35.                     positionForTExt = positionForTExt + 1;
  36.                 }
  37.             }
  38.         }
  39.     }
  40.  
  41.     public static int[] computeLPS(String pattern) {
  42.         if (pattern == null || pattern.isEmpty()) {
  43.             return null;
  44.         }
  45.         int[] lps = new int[pattern.length()];
  46.         int index = 1;
  47.         lps[0] = 0;
  48.         int curLen = 0;
  49.         while (index < pattern.length()) {
  50.             if (pattern.charAt(index) == pattern.charAt(curLen)) {
  51.                 curLen++;
  52.                 lps[index] = curLen;
  53.                 index++;
  54.             } else {
  55.                 if (curLen != 0) {
  56.                     curLen = lps[curLen - 1];
  57.  
  58.                 } else {
  59.                     lps[index] = curLen;
  60.                     index++;
  61.                 }
  62.             }
  63.         }
  64.         System.out.println("LPS of: " + pattern);
  65.         for (int i : lps) {
  66.             System.out.print(i + " ");
  67.         }
  68.         return lps;
  69.  
  70.     }
  71. }
Add Comment
Please, Sign In to add comment