1
1
package problems .onRecursionAndDp .dp ;
2
2
3
3
public class EditDistance {
4
+ public int minDistance (String word1 , String word2 ) {
5
+ int dp [][] = new int [word1 .length ()+1 ][word2 .length ()+1 ];
6
+
7
+ //insertion needed for all chars in first row
8
+ //to convert "" to word2
9
+ for (int col =1 ;col <=word2 .length ();col ++)
10
+ dp [0 ][col ] = dp [0 ][col -1 ] + 1 ;
11
+
12
+ //deletion needed in 1st column to convert word2 to "" blank string
13
+ for (int row =1 ;row <=word1 .length ();row ++)
14
+ dp [row ][0 ] = dp [row -1 ][0 ] + 1 ;
15
+
16
+ //to fill remaining matrix
17
+ for (int row =1 ;row <=word1 .length ();row ++){
18
+ for (int col =1 ;col <=word2 .length ();col ++){
19
+ if (word1 .charAt (row -1 ) == word2 .charAt (col -1 )) {
20
+ dp [row ][col ] = dp [row -1 ][col -1 ];
21
+ continue ;
22
+ }
23
+ //when we replace char in word1 to given char at word2
24
+ //then we min value for match of string 0 to row-1 to 0 to col-1
25
+ //which is found in block row-1, col-1.
26
+ int replaceval = dp [row -1 ][col -1 ];
27
+
28
+ //when we delete character in word1 then what we are saying is we
29
+ //want min for match of pattern 0 to row-1 of word1
30
+ //to 0 to col of word2
31
+ int deleteval = dp [row -1 ][col ];
32
+
33
+ //when we insert value in word1 what this means is
34
+ //we need to find min value for conversion of substring 0 to row from word1
35
+ //to 0 to col-1 in word2 as colth char is inserted in word1
36
+ int insval = dp [row ][col -1 ];
37
+
38
+ dp [row ][col ] = Math .min (replaceval , Math .min (deleteval , insval )) + 1 ;
39
+ //add cost of operation -> 1 only when characters in that position are not //same
40
+
41
+ }
42
+ }
43
+ return dp [word1 .length ()][word2 .length ()];
44
+ }
45
+
4
46
}
47
+
48
+ /**
49
+ * 72. Edit Distance
50
+ * Hard
51
+ *
52
+ * 2799
53
+ *
54
+ * 44
55
+ *
56
+ * Add to List
57
+ *
58
+ * Share
59
+ * Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
60
+ *
61
+ * You have the following 3 operations permitted on a word:
62
+ *
63
+ * Insert a character
64
+ * Delete a character
65
+ * Replace a character
66
+ * Example 1:
67
+ *
68
+ * Input: word1 = "horse", word2 = "ros"
69
+ * Output: 3
70
+ * Explanation:
71
+ * horse -> rorse (replace 'h' with 'r')
72
+ * rorse -> rose (remove 'r')
73
+ * rose -> ros (remove 'e')
74
+ * Example 2:
75
+ *
76
+ * Input: word1 = "intention", word2 = "execution"
77
+ * Output: 5
78
+ * Explanation:
79
+ * intention -> inention (remove 't')
80
+ * inention -> enention (replace 'i' with 'e')
81
+ * enention -> exention (replace 'n' with 'x')
82
+ * exention -> exection (replace 'n' with 'c')
83
+ * exection -> execution (insert 'u')
84
+ **/
0 commit comments