Delete Operations for Two Strings in C++


Suppose we have two words w1 and w2, we have to find the minimum number of steps required to make w1 and w2 the same, where in each step we can delete one character in either string. So if the input is like “sea” and “eat”, then the output will be 2, because we need to delete ‘s’ from w1, this will be “ea” and delete “t” from “eat” from w2. Then they are the same.

To solve this, we will follow these steps

  • n := size of s1, m := size of s2
  • add one blank space before the strings s1 and s2, then update the s1 and s2 accordingly
  • make one table of size (n + 1) x (m + 1)
  • for i := 1 to m
    • dp[0, i] := dp[0, i - 1] + 1
  • for i := 1 to n
    • dp[i, 0] := dp[i – 1, 0] + 1
  • for i in range 1 to n
    • for j in range 1 to m
      • if s1[i] = s2[j]
        • dp[i, j] := dp[i – 1, j - 1]
      • else dp[i, j] = minimum of dp[i – 1, j] + 1 and dp[i, j - 1] + 1
  • return dp[n, m]

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int minDistance(string s1, string s2) {
      int n = s1.size();
      int m = s2.size();
      s1 = " " + s1;
      s2 = " " + s2;
      vector < vector <int> > dp(n + 1, vector <int>(m + 1));
      for(int i = 1; i <= m; i++){
         dp[0][i] = dp[0][i - 1] + 1;
      }
      for(int i = 1; i <= n; i++){
         dp[i][0] = dp[i - 1][0] + 1;
      }
      for(int i = 1; i <= n; i++){
         for(int j = 1; j <= m; j++){
            if(s1[i] == s2[j]){
               dp[i][j] = dp[i - 1][j - 1];
            }
            else{
               dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1);
            }
         }
      }
      return dp[n][m];
   }
};
main(){
   Solution ob;
   vector<int> v = {1,1,1};
   cout << (ob.minDistance("sea", "eat"));
}

Input

"sea"
"eat"

Output

2

Updated on: 29-Apr-2020

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements