Question:
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].
Solution:
这道题就是编辑距离问题,不同的是,只可以删除。因此,用cost[i][j] 表示把字符串s1[1, i]和s2[1, j]弄成相同字符串的代价。初始化时,
1. cost[0][0] 为 0
2. cost[i][0] = cost[i-1][0] + s1[i] 因为cost[i][0] 表示把字符串s1[1, i]完全删除的代价
3. cost[0][j] = cost[0][j-1] + s2[j] 理由同上
然后对于其他cost[i][j] ,状态转移方程为:
cost[i][j] = min (cost[i][j-1] + s2[j], cost[i-1][j] + s1[i] + cost[i-1][j-1] + diff(s1[i]+s2[j]))
也即要将s1[1, i]和s2[1, j]弄成完全相同,要么是把其中一个字符串最后一个字母(s1[i]或s2[j])删掉,要么是相同的时候直接等于cost[i-1][j-1]
最后只要返回cost[s1.size()][s2.size()] 即可。
时间复杂度:O(mn)
空间复杂度:O(mn)
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
int cost[s1.size()+1][s2.size()+1];
// cost[0][0] ... cost[0][j]
cost[0][0] = 0;
for (int i = 0; i < s2.size(); i++) {
cost[0][i+1] = cost[0][i] + s2[i];
}
// cost[1][0] ... cost[i][0]
for (int i = 0; i < s1.size(); i++) {
cost[i+1][0] = cost[i][0] + s1[i];
}
for (int i = 1; i <= s1.size(); i++) {
cost[0][i+1] = cost[0][i] + s2[i];
for (int j = 1; j <= s2.size(); j++) {
cost[i][j] = min(cost[i][j-1] + s2[j-1], cost[i-1][j] + s1[i-1]);
cost[i][j] = min(cost[i][j], cost[i-1][j-1] + diff(s1[i-1], s2[j-1]));
}
}
return cost[s1.size()][s2.size()];
}
int diff(char ch1, char ch2) {
if (ch1 == ch2)
return 0;
else
return (ch1 + ch2);
}
};