Skip to content

Commit 290131b

Browse files
Create Day 31 Edit Distance.cpp
1 parent 8b68b9d commit 290131b

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

Day 31 Edit Distance.cpp

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
PROBLEM:
2+
3+
4+
5+
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
6+
You have the following 3 operations permitted on a word:
7+
8+
Insert a character
9+
Delete a character
10+
Replace a character
11+
12+
Example 1:
13+
Input: word1 = "horse", word2 = "ros"
14+
Output: 3
15+
16+
Explanation:
17+
horse -> rorse (replace 'h' with 'r')
18+
rorse -> rose (remove 'r')
19+
rose -> ros (remove 'e')
20+
21+
Example 2:
22+
Input: word1 = "intention", word2 = "execution"
23+
Output: 5
24+
25+
Explanation:
26+
intention -> inention (remove 't')
27+
inention -> enention (replace 'i' with 'e')
28+
enention -> exention (replace 'n' with 'x')
29+
exention -> exection (replace 'n' with 'c')
30+
exection -> execution (insert 'u')
31+
32+
33+
34+
35+
36+
SOLUTION:
37+
38+
39+
class Solution {
40+
public:
41+
int minDistance(string word1, string word2) {
42+
43+
int i,j,n,m;
44+
n = word1.size();
45+
m = word2.size();
46+
47+
vector<vector<int>> dp(n+1,vector<int>(m+1,0));
48+
49+
for(i=0;i<=n;i++)
50+
{
51+
for(j=0;j<=m;j++)
52+
{
53+
if(i==0)
54+
dp[i][j]=j;
55+
56+
else if(j==0)
57+
dp[i][j]=i;
58+
59+
else if(word1[i-1] == word2[j-1])
60+
dp[i][j] = dp[i-1][j-1];
61+
62+
else
63+
dp[i][j] = 1 + min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]});
64+
}
65+
}
66+
67+
68+
return dp[n][m];
69+
}
70+
};

0 commit comments

Comments
 (0)