712. Minimum ASCII Delete Sum for Two Strings
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]
.
1.解析
题目大意,求解两个字符串相等,所删除字符对应的ASCII 值的和最小。
2.分析
这道题的本质和Delete Operation for Two Strings是一样的,不同在于一个求长度,一个求对应ASCII值,即递推公式表示的含义不一样。我最初没想出来,应该是举一反三的能力还有待欠缺。参考@Grandyang博主的思路,利用dp[i][j]表示s1前i个字符,s2前j个字符所代表的字符串相同时,所对应ASCII值的和的最大值。递推的过程类似最长公共子序列,可以具体参考我这篇博客Delete Operation for Two Strings。最后用两个字符串总的和减去当前最大值的2倍即为所剩的最小值。
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 i = 1; i <= m; ++i){
for (int j = 1; j <= n; ++j){
if (s1[i-1] == s2[j-1]) dp[i][j] = dp[i-1][j-1] + s1[i-1]; //当前两个字符相等,即不用删除
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]); //若不相等,取前[i, j]区间内的最大值
}
}
int sum1 = accumulate(s1.begin(), s1.end(), 0);
int sum2 = accumulate(s2.begin(), s2.end(), 0);
return sum1 + sum2 - 2 * dp[m][n]; //两者的和减去当前最大值,即为所求的最小值
}
};