Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create editDistance.cpp #482

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions 20. Dynamic Programming/editDistance.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution {
public:
int minDistance(string s1, string s2) {
int n = s1.size();
int m = s2.size();
// vector<vector<int>> dp(n+1, vector<int>(m+1, -1));
vector<int> prev(m+1, -1), curr(m+1, -1);

// for(int i = 0; i <= n; i++) dp[i][0] = i; //Covered in the nested for
for(int j = 0; j <= m; j++) prev[j] = j;

for(int i = 1; i<=n; i++){
curr[0] = i;
for(int j = 1; j<=m; j++){
if(s1[i-1] == s2[j-1]) curr[j] = 0 + prev[j-1] ;
else{
curr[j] = 1 + min(prev[j], //delete
min(curr[j-1], //insert
prev[j-1])); //replace
}
}
prev = curr;
}

return prev[m];
}
};