import java.util.Scanner; public class MED_ver2 { /* ============================================== T(x,y) = cost to transform x --> y ============================================== */ static int T(String x, String y) { int sol1, sol2, sol3, MySol=0; /* --------------------------- Base cases --------------------------- */ if ( x.length() == 0 ) { return(y.length()); // insertion all chars of y } if ( y.length() == 0 ) { return(x.length()); // delete all chars in x } int i = x.length(); int j = y.length(); /* --------------------------- The other cases.... --------------------------- */ if ( x.charAt(i-1) == y.charAt(j-1) ) { sol1 = T(x.substring(0,i-1), y.substring(0,j-1)); MySol = sol1; // No further edit necessary return(MySol); } else { /* ------------------------------------------------------ Last edit operation on x must be one of these: 1. delete last char 2. insert the last char of y to x 3. replace last char of x to the last char of y ------------------------------------------------------- */ sol1 = T(x.substring(0,i-1), y); // Cost if delete step as last sol2 = T(x, y.substring(0,j-1)); // Cost if insert step as last sol3 = T(x.substring(0,i-1), y.substring(0,j-1)); // Cost if 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); System.out.println("Min. Edit Distance = " + r); } }