The Java Program: Approx.java

  1 // Approx.java -- approximate string matching
  2 
  3 class Approx  {
  4 
  5    static boolean match (int K, char pattern[], char text[]) {
  6       int M   = pattern.length;  //length of pattern
  7       int N   = text.length; //length of string to be matched
  8       int T[] = new int[M+1];
  9 
 10       // If you can have more substitutions than you have characters
 11       // in the pattern, then any substring in the text will do.
 12       if (M <= K) return true;
 13          
 14       for (int j = 0; j <= M; j++)  T[j] = j;
 15 
 16       //Search the text from the end to the beginning
 17       for (int i=N-1; i >= 0; i--) {
 18          int Tj1 = 0;
 19          for (int j=1; j <= M; j++) {
 20             int Tj = T[j];
 21             if (text[i] != pattern[M-j]) Tj1++;
 22                   
 23             // T[j] = Min (Tj1, Tj+1, T[j-1]+1)
 24             if (Tj+1 < Tj1)        Tj1 = Tj + 1;
 25             if ((T[j-1]+1) < Tj1)  Tj1 = T[j-1]+1;
 26             T[j] = Tj1;
 27                                         
 28             Tj1 = Tj;
 29          }
 30 
 31          // T[M] is the number of errors needed so the entire pattern
 32          // (characters 1..M) matches the text (beginning at position i)
 33          if (T[M] <= K)  return true;
 34       }
 35       return false;
 36    }
 37 
 38    public static void main (String args[]) {
 39       int K;
 40       char pattern[], text[];
 41       try {
 42          K        = Integer.parseInt(args[0]);
 43          pattern  = args[1].toCharArray(); 
 44          text     = args[2].toCharArray(); 
 45       } catch (ArrayIndexOutOfBoundsException e) {
 46          System.out.println ("Must provide exactly three arguments.");
 47          return;
 48       } catch (NumberFormatException e) {
 49          System.out.println ("The first argument must be an integer.");
 50          return;
 51       }
 52 
 53       if (match (K, pattern, text)) {
 54          System.out.println("Match.");
 55       } else {
 56          System.out.println("No match.");
 57       }
 58    }
 59 }