Minimum ASCII Delete Sum for Two Strings in C++

C++Server Side ProgrammingProgramming

Suppose we have two words w1 and w2, we have to find the lowest ASCII sum of deleted characters 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 231, because we need to delete ‘s’ from w1, this will be “ea” and delete “t” from “eat” from w2. Then they are same. Deleting ‘t’ from “eat” adds 116 to the sum, and at the end, both strings are the same and 115 + 116 = 231 is the minimum sum possible to achieve this.

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] + s2[i]
  • for i := 1 to n
    • dp[i, 0] := dp[i – 1, 0] + s1[i]
  • 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 minimumDeleteSum(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] + s2[i];
      }
      for(int i = 1; i <= n; i++){
         dp[i][0] = dp[i - 1][0] + s1[i];
      }
      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] + s1[i], dp[i][j - 1] + s2[j]);
            }
         }
      }
      return dp[n][m];
   }
};
main(){
   Solution ob;
   cout << (ob.minimumDeleteSum("sea", "eat"));
}

Input

"sea"
"eat"

Output

231
raja
Published on 27-Feb-2020 10:50:46
Advertisements