Given two strings, return the lowest ASCII sum of the deleted characters to make the strings equal.


Returning the lowest ASCII sum of deleted characters to make two strings equal is equivalent to finding the maximum ASCII of a common subsequence.  This problem is a variant of the Longest Common Subsequence (LCS). 

Instead of looking for the length of the longest common subsequence, we'll look for the maximum ASCII sum of a common subsequence.  This solves situations like shown in the example test case, when the string "eet" is chosen over "let".

Altering LCS for ASCII sum requires only one change in the recursive function.  In the recurrence relation, when the characters of the two strings are equal, rather than adding 1 for a path length, we add the ASCII total to the answer

    int ans;
if(str1[i]==str2[j]) {
ans=(int)str1[i]+dp(i+1, j+1);
} else {
ans = max(dp(i+1,j),dp(i,j+1));
}

Then in the main function, we add a few lines for ASCII sum calculations

We find the ASCII totals for each string

    int total=0;
for(int i=0; i<s1.size(); i++) total+=(int)s1[i];
for(int i=0; i<s2.size(); i++) total+=(int)s2[i];

And we subtract from the total the ASCII value of the largest common subsequence multiplied by 2, since the substring occurs in both of the original strings

int lce = dp(0,0);

return total-lce*2;

Good problem, fun to get to play around with facets of LCS

Full code below:

vector<vector<int> >memo;
string str1, str2;

int dp(int i, int j) {
if(i==str1.size() || j==str2.size()) return 0;

if(memo[i][j]!=-1) return memo[i][j];

int ans;
if(str1[i]==str2[j]) {
ans=(int)str1[i]+dp(i+1, j+1);
} else {
ans = max(dp(i+1,j),dp(i,j+1));
}

return memo[i][j]=ans;
}

int minimumDeleteSum(string s1, string s2) {
str1=s1;
str2=s2;
memo=vector<vector<int> >(s1.size()+1, vector<int>(s2.size()+1, -1));

int lce = dp(0,0);

int total=0;
for(int i=0; i<s1.size(); i++) total+=(int)s1[i];
for(int i=0; i<s2.size(); i++) total+=(int)s2[i];

return total-lce*2;
}





Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th