|
| 1 | +/* A Dynamic Programming based Java program to find minimum number operations to convert String1 to String2 */ |
| 2 | +class EditDistance |
| 3 | +{ |
| 4 | + static int min(int x,int y,int z) |
| 5 | + { |
| 6 | + if (x <= y && x <= z) |
| 7 | + return x; |
| 8 | + if (y <= x && y <= z) |
| 9 | + return y; |
| 10 | + else |
| 11 | + return z; |
| 12 | + } |
| 13 | + |
| 14 | + static int editDistDP(String str1, String str2, int m, int n) |
| 15 | + { |
| 16 | + // Create a table to store results of subproblems |
| 17 | + int dp[][] = new int[m+1][n+1]; |
| 18 | + |
| 19 | + // Fill d[][] in bottom up manner |
| 20 | + for (int i=0; i<=m; i++) |
| 21 | + { |
| 22 | + for (int j=0; j<=n; j++) |
| 23 | + { |
| 24 | + // If first string is empty, only option is to |
| 25 | + // insert all characters of second string |
| 26 | + if (i==0) |
| 27 | + dp[i][j] = j; // Min. operations = j |
| 28 | + |
| 29 | + // If second string is empty, only option is to |
| 30 | + // remove all characters of second string |
| 31 | + else if (j==0) |
| 32 | + dp[i][j] = i; // Min. operations = i |
| 33 | + |
| 34 | + // If last characters are same, ignore last char |
| 35 | + // and recur for remaining string |
| 36 | + else if (str1.charAt(i-1) == str2.charAt(j-1)) |
| 37 | + dp[i][j] = dp[i-1][j-1]; |
| 38 | + |
| 39 | + // If the last character is different, consider all |
| 40 | + // possibilities and find the minimum |
| 41 | + else |
| 42 | + dp[i][j] = 1 + min(dp[i][j-1], // Insert |
| 43 | + dp[i-1][j], // Remove |
| 44 | + dp[i-1][j-1]); // Replace |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return dp[m][n]; |
| 49 | + } |
| 50 | + |
| 51 | + public static void main(String args[]) |
| 52 | + { |
| 53 | + String str1 = "Rohan"; //1st String that need to be converted to 2nd String |
| 54 | + String str2 = "Roushan"; //2nd String |
| 55 | + System.out.println( editDistDP( str1 , str2 , str1.length(), str2.length()) ); |
| 56 | + } |
| 57 | +} |
| 58 | + |
0 commit comments