Skip to content

Commit 38a4f83

Browse files
authored
Create 31 - Edit Distance.cpp
1 parent 247e45b commit 38a4f83

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

31 - Edit Distance.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public:
3+
int minDistance(string word1, string word2) {
4+
5+
vector < vector <int> > dp(word1.size()+1, vector <int> (word2.size()+1, 0));
6+
7+
for(int i = 1; i<=word1.size(); i++){
8+
dp[i][0] = dp[i-1][0] + 1;
9+
}
10+
11+
for(int i = 1; i<=word2.size(); i++){
12+
dp[0][i] = dp[0][i-1] + 1;
13+
}
14+
15+
for(int i = 1; i<=word1.size(); i++){
16+
for(int j = 1; j<=word2.size(); j++){
17+
if(word1[i-1] != word2[j-1]){
18+
dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;
19+
}
20+
else{
21+
dp[i][j] = dp[i-1][j-1];
22+
}
23+
}
24+
}
25+
26+
return dp[word1.size()][word2.size()];
27+
}
28+
};

0 commit comments

Comments
 (0)