File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ public class MinimumEditDistance {
2+ public static void main (String [] args ) {
3+ String str1 = "kitten" ;
4+ String str2 = "sitting" ;
5+ System .out .println ("Minimum Edit Distance between \" " + str1 + "\" and \" " + str2 + "\" is: " + minEditDistance (str1 , str2 ));
6+ }
7+
8+ public static int minEditDistance (String str1 , String str2 ) {
9+ int m = str1 .length ();
10+ int n = str2 .length ();
11+ int [][] dp = new int [m + 1 ][n + 1 ];
12+
13+ for (int i = 0 ; i <= m ; i ++) {
14+ for (int j = 0 ; j <= n ; j ++) {
15+ if (i == 0 ) {
16+ dp [i ][j ] = j ; // Insert all characters of str2
17+ } else if (j == 0 ) {
18+ dp [i ][j ] = i ; // Remove all characters of str1
19+ } else if (str1 .charAt (i - 1 ) == str2 .charAt (j - 1 )) {
20+ dp [i ][j ] = dp [i - 1 ][j - 1 ]; // Characters match
21+ } else {
22+ dp [i ][j ] = 1 + Math .min (dp [i - 1 ][j ], // Remove
23+ Math .min (dp [i ][j - 1 ], // Insert
24+ dp [i - 1 ][j - 1 ])); // Replace
25+ }
26+ }
27+ }
28+ return dp [m ][n ];
29+ }
30+ }
You can’t perform that action at this time.
0 commit comments