[LeetCode] 646. Maximum Length of Pair Chain
题目描述
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].
分析
维护一个cost的二维表。
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[0][j]表示把字符串s2从(1, i)完全删除的代价
4. 对于其他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])) 前一个字符相同时,cost[i][j]与cost[i-1][j-1]相同,否则就删除s1[i]或者s2[j],取决于哪个的代价更小。
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
int cost[s1.size()+1][s2.size()+1];
cost[0][0] = 0;
for (int i = 0; i < s2.size(); i++) {
cost[0][i+1] = cost[0][i] + s2[i];
}
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++) {
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()];
}
private:
int diff(char i, char j) {
return i == j ? 0 : i + j;
}
};