- descrption
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]. - 解题思路
题意是将两个字符串删除个别字符后得到相同的字符串,求得删除字符的ASCII码的值的最小和,那么反向思考也是求得剩下字符的ASCII码的和的最大值,因为字符串中字符的总的ASCII码值的总和是不变的。下面就可以将问题转化为:求得两个字符串中公共子序列的最大的ASCII码值的和,对求最长公共子序列的方法稍加改变就可得到该问题的答案。
求解最长子序列的状态转移方程为:
用l[i][j]记录以s1[i]和s2[j]结尾的最长子序列的长度
if s1[i] == s2[j]
l[i][j] = l[i-1][j-1] + 1;
else
l[i][j] = max(l[i-1][j], l[i][j-1]);
==========================================================
求解该问题的状态转移方程为:
用dp[i][j]记录以s1[i]和s2[j]结尾的子序列的最大的ASCII码值的总和
if s1[i] == s2[j]
dp[i][j] = dp[i-1][j-1] + (int)s1[i];
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
- 代码如下
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
int len1 = s1.length();
int len2 = s2.length();
int dp[len1+1][len2+1];
memset(dp, 0, sizeof(dp));
for (int i = 0; i < len1; i++) {
for (int j = 0; j < len2; 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]);
}
}
}
int all = 0;
for(int i = 0; i < len1; i ++) {
all += (int)s1[i];
}
for(int j = 0; j < len2; j ++) {
all += (int)s2[j];
}
return all - 2*dp[len1][len2];
}
};
如有错误请指出,谢谢!