week10
题目
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].
原题地址:https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/
解析
本题与编辑距离的思想相同,唯一的不同是将字符串中字符的ASCII的值作为代价。
用一个二维数组deleteSum,deleteSum[i][j]表示第一个字符串前i个字符组成的子串和第二个字符串前j个字符组成的子串的编辑距离(以字符的ASCII的值为代价,下同)。
deleteSum[i][0]表示第一个字符串前i个字符组成的子串与空串的编辑距离,为第一个字符串前i个字符的ASCII值的和,因为该子串要等于空串需把所有字符删除,同理deleteSum[0][j]为第二个字符串的前j个字符的ASCII值的和。
而其他的deleteSum[i][j]可转为为子问题deleteSum[i-1][j],deleteSum[i][j-1]或deleteSum[i-1][j-1]进一步解决
代码
class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
int **deleteSum = new int*[s1.size() + 1];
for (int i = 0; i < s1.size() + 1; ++i) {
deleteSum[i] = new int[s2.size() + 1];
for (int j = 0; j < s2.size() + 1; ++j) {
deleteSum[i][j] = 0;
}
}
for (int i = 1; i < s1.size() + 1; ++i) {
deleteSum[i][0] = deleteSum[i - 1][0] + s1[i - 1];
}
for (int j = 1; j < s2.size() + 1; ++j) {
deleteSum[0][j] = deleteSum[0][j - 1] + s2[j - 1];
}
for (int i = 1; i < s1.size() + 1; ++i) {
for (int j = 1; j < s2.size() + 1; ++j) {
int diff = s1[i - 1] == s2[j - 1] ? 0 : s1[i - 1] + s2[j - 1];
deleteSum[i][j] = min(s1[i - 1] + deleteSum[i - 1][j],
s2[j - 1] + deleteSum[i][j - 1], deleteSum[i - 1][j - 1] + diff);
}
}
return deleteSum[s1.size()][s2.size()];
}
int min(int a, int b, int c) {
int tmp = a;
if (b < tmp) {
tmp = b;
}
if (c < tmp) {
tmp = c;
}
return tmp;
}
};