import java.util.Scanner; public class MED { /* ---------------------- i = # chars in x j = # chars in y ---------------------- */ static int T(String x, String y, int i, int j) { int sol1, sol2, sol3, MySol=0; /* --------------------------- Base cases --------------------------- */ if ( i == 0 ) { return(j); // j insertions } if ( j == 0 ) { return(i); // i deletions... } /* --------------------------- The other cases.... --------------------------- */ if ( x.charAt(i-1) == y.charAt(j-1) ) { sol1 = T(x, y, i-1, j-1); MySol = sol1; // No further edit necessary return(MySol); } else { /* ------------------------ Divide step ------------------------ */ sol1 = T(x, y, i-1, j); // Try delete step as last sol2 = T(x, y, i, j-1); // Try insert step as last sol3 = T(x, y, i-1, j-1); // Try replace step as last /* --------------------------------------- Conquer: solve original problem using solution from smaller problems --------------------------------------- */ sol1 = sol1 + 1; sol2 = sol2 + 1; sol3 = sol3 + 1; if ( sol1 <= sol2 && sol1 <= sol3 ) MySol = sol1; // Sol1 is best if ( sol2 <= sol1 && sol2 <= sol3 ) MySol = sol2; // Sol2 is best if ( sol3 <= sol1 && sol3 <= sol2 ) MySol = sol3; // Sol3 is best return(MySol); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); String x; String y; int r; System.out.print("String x = "); x = in.next(); System.out.print("String y = "); y = in.next(); r = T(x, y, x.length(), y.length()); System.out.println("Min. Edit Distance = " + r); } }