1 题目
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",
adds 100[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.
Note:
0 < s1.length, s2.length <= 1000
.- All elements of each string will have an ASCII value in
[97, 122]
.
2 题目
2.1 分析
给定两个字符串S1和S2,可以对其执行删除操作。每次操作可以删除字符串S1或S2中的一个字母,操作的代价即为该字母在ASCII中的值。问怎样以最小的代价使得S1和S2变为相同的字符串。
sum(string s)代表字符串S所有字符ASCII值之和。假设操作完成后,S1和S2均成为字符串S,则操作的代价为cost=sum(S1)+sum(S2)-2sum(S),最小化代价即最大化sum(S)。
如果ASCII(a) = 1, ASCII(z) = 26,则zaa和aaz最小代价的删除操作后,剩余的字符串是aa而不是z,即删除两次的代价可能比删除一次的更小。但是所有字母的ASCII值均大于26,且连续分布,所以删除两次的代价绝对比删除一次的要大,所以删除的越少越好,即S越长越好。则该问题变为对于所有的S∈CommonMaxSubsequence(S1,S2)(最长公共子序列),问min(S)。
另一种思路与此相似,但是不用考虑在aaz和zaa中删除一次还是两次的问题。即将最长公共子序列转变为求最大成本公共子序列,只需要将选择的成本换为字母的ASCII值即可,即下列代码所示。
2.2 代码
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
int result = 0;
vector<vector<int>> count(s1.size(),vector<int>(s2.size(),0));
for(auto letter : s1) result += letter;
for(auto letter : s2) result += letter;
for(int i = 0; i < s1.size(); i++){
for(int j = 0; j < s2.size(); j++){
if(s1[i]==s2[j]){
count[i][j]=s1[i] + (i*j?count[i-1][j-1]:0);
}
else{
count[i][j]=max(i?count[i-1][j]:0,j?count[i][j-1]:0);
}
}
}
return result-2*count.back().back();
}
};
3 标准解
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
int m = s1.size(), n = s2.size();
vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
for (int j = 1; j <= n; j++)
dp[0][j] = dp[0][j-1]+s2[j-1];
for (int i = 1; i <= m; i++) {
dp[i][0] = dp[i-1][0]+s1[i-1];
for (int j = 1; j <= n; j++) {
if (s1[i-1] == s2[j-1])
dp[i][j] = dp[i-1][j-1];
else
dp[i][j] = min(dp[i-1][j]+s1[i-1], dp[i][j-1]+s2[j-1]);
}
}
return dp[m][n];
}
};