1. Description
Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.
Example 1:
Input: s1 = “sea”, s2 = “eat”
Output: 231
Explanation: Deleting “s” from “sea” adds the ASCII value of “s” (115) to the sum.
Deleting “t” from “eat” adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
Example 2:
Input: s1 = “delete”, s2 = “leet”
Output: 403
Explanation: Deleting “dee” from “delete” to turn the string into “let”,adds100[d]+101[e]+101[e] to the sum. Deleting “e” from “leet” adds 101[e] to the sum.
At the end, both strings are equal to “let”, and the answer is 100+101+101+101 = 403.
If instead we turned both strings into “lee” or “eet”, we would get answers of 433 or 417, which are higher.
2. Analysis
这道题其实是关于寻找最长公共子序列的变体,题目要求的是被剔除的字符的最小ASCII码总和,把问题倒过来看,在保证最长子序列的基础上,寻找这个最小ACSII码总和,如此一来,只需要修改一下求救最长子序列的程序就能找出来。
而最长子序列的情况无非以下三种:
- 当 Si+1=Ti+1 时,在 S1...Si 和 T1...Ti 的公共子序列末尾加上 Si+1
- S1...Si+1 和 T1...Ti 的公共自序列
- S1...Si 和 T1...Ti+1 的公共子序列
得到求解最长子序列长度的状态转移方程为:
3. Code
#include<iostream>
#include<string.h>
#include<string>
using namespace std;
int max(int a, int b) {
return a>b? a:b;
}
int minimumDeleteSum(string s1, string s2) {
string res = "";
int dp[s1.length()+1][s2.length()+1];
memset(dp, 0, sizeof(dp));
int sum = 0;
//find the longest common sub sequence between s1 and s2
// find the total ASCII value of the subString
// if the value is largest, delete sum will be lowest
for(int i = 0; i < s1.length(); i++) {
sum += (int)s1[i];
for(int j = 0; j < s2.length(); j++) {
if(s1[i] == s2[j]) {
dp[i+1][j+1] = dp[i][j] + (int)s1[i];
} else {
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);
}
}
}
for(int j = 0; j < s2.length();j ++) {
sum += (int)s2[j];
}
return sum - 2*dp[s1.length()][s2.length()];
}
int main() {
string s1 = "delete";
int sum = 0;
cout << minimumDeleteSum(s1,"leet") <<endl;
for(int i=0; i < s1.length(); i++) {
cout << (int)s1[i] << endl;
sum += (int)s1[i];
}
cout << sum <<endl;
}