From 45ab26ee0ac24471f196f68fa89a588826dfe358 Mon Sep 17 00:00:00 2001 From: Vaibhav Kesarwani <54628220+MeVaibhav9@users.noreply.github.com> Date: Mon, 31 Oct 2022 18:01:02 +0530 Subject: [PATCH] Create editDistance.cpp --- 20. Dynamic Programming/editDistance.cpp | 27 ++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 20. Dynamic Programming/editDistance.cpp diff --git a/20. Dynamic Programming/editDistance.cpp b/20. Dynamic Programming/editDistance.cpp new file mode 100644 index 0000000..62a6718 --- /dev/null +++ b/20. Dynamic Programming/editDistance.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int minDistance(string s1, string s2) { + int n = s1.size(); + int m = s2.size(); + // vector> dp(n+1, vector(m+1, -1)); + vector 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]; + } +};