File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* problem statement -> https://leetcode.com/problems/edit-distance/
2
+
3
+ Description ->
4
+ Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.
5
+
6
+ You have the following three operations permitted on a word:
7
+
8
+ Insert a character
9
+ Delete a character
10
+ Replace a character
11
+
12
+
13
+ Example -> word1 = "horse", word2 = "ros"
14
+ Output -> 3
15
+ horse -> rorse (replace 'h' with 'r')
16
+ rorse -> rose (remove 'r')
17
+ rose -> ros (remove 'e')
18
+ */
19
+
20
+ #include < bits/stdc++.h>
21
+ using namespace std ;
22
+
23
+ int minDistance (string word1, string word2) {
24
+ int n = word1.length ();
25
+ int m = word2.length ();
26
+ // dp array
27
+ int dp[n+1 ][m+1 ];
28
+ // empty string to empty -> no change
29
+ dp[0 ][0 ]=0 ;
30
+
31
+ // To convert a string to a empty string, or
32
+ // To convert empty string to string use (length => i or j) operations
33
+ for (int j=1 ;j<m+1 ;j++)
34
+ dp[0 ][j]=j;
35
+ for (int i=1 ;i<n+1 ;i++)
36
+ dp[i][0 ]=i;
37
+
38
+ for (int i=1 ;i<n+1 ;i++)
39
+ {
40
+ for (int j=1 ;j<m+1 ;j++)
41
+ {
42
+ // if word[i-1]==word[j-1]; dp[i][j] is same as dp[i-1][j-1]
43
+ if (word1[i-1 ]==word2[j-1 ])
44
+ dp[i][j] = dp[i-1 ][j-1 ];
45
+ else
46
+ // 3 cases of insert(dp[i-1][j]), delete(dp[i][j-1]), replace(dp[i-1][j-1])+1
47
+ dp[i][j] = min (dp[i-1 ][j-1 ], min (dp[i-1 ][j], dp[i][j-1 ]))+1 ;
48
+ }
49
+ }
50
+ // ans is last element
51
+ return dp[n][m];
52
+ }
53
+
54
+ int main ()
55
+ {
56
+ string w1;
57
+ string w2;
58
+ cin>>w1>>w2;
59
+ // calling the minDistance function
60
+ int ans = minDistance (w1, w2);
61
+ cout<<ans<<" \n " ;
62
+ return 0 ;
63
+ }
You can’t perform that action at this time.
0 commit comments