File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
May-LeetCoding-Challenge/31-Edit-Distance Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Dynamic programming, operation of previous string plus one if the last character is not the same
3
+ * XXXb -> YYYc => operation(XXX to YYY) + 1
4
+ * XXXm -> XXXm => operation(XXX to YYY)
5
+ */
6
+ class Solution {
7
+ public int minDistance (String word1 , String word2 ) {
8
+ int m = word1 .length (), n = word2 .length ();
9
+ int dp [][] = new int [m +1 ][n +1 ];
10
+
11
+ /**
12
+ * Construct a dp table
13
+ * __|''|a|b|c|
14
+ * ''| 0|1|2|3|...
15
+ * ''| 0
16
+ * d | 1
17
+ * e | 2
18
+ * f | 3
19
+ */
20
+ for (int i = 0 ; i <= m ; i ++) {
21
+ dp [i ][0 ] = i ;
22
+ }
23
+
24
+ for (int j = 0 ; j <= n ; j ++) {
25
+ dp [0 ][j ] = j ;
26
+ }
27
+
28
+ for (int i = 0 ; i < m ; i ++) {
29
+ for (int j = 0 ; j < n ; j ++) {
30
+ char c1 = word1 .charAt (i );
31
+ char c2 = word2 .charAt (j );
32
+
33
+ // If the last character is the same, we do nothing compare to previous string
34
+ if (c1 == c2 ) {
35
+ dp [i + 1 ][j + 1 ] = dp [i ][j ];
36
+ } else {
37
+ // we chose the minimum operation of three operation: insert, delete, replace
38
+ dp [i + 1 ][j + 1 ] = Math .min (dp [i ][j ], Math .min (dp [i +1 ][j ], dp [i ][j +1 ])) + 1 ;
39
+ }
40
+ }
41
+ }
42
+
43
+ return dp [m ][n ];
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments