题目:
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码最大的公共子序列。这样最终的结果就是s1和s2的ASCII码之和减去ASCII码最大的公共子序列的2倍。
这里实现的版本的时间复杂度是O(mn),空间复杂度是O(mn)。但是空间复杂度还可以降低到O(m)或者O(n)。
代码:
class Solution { public: int minimumDeleteSum(string s1, string s2) { int len1 = s1.length(), len2 = s2.length(); vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1, 0)); for (int i = 1; i <= len1; ++i) { for (int j = 1; j <= len2; ++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]); } } } int ret = 0; for(int i = 0; i < len1; ++i) { ret += s1[i]; } for (int i = 0; i < len2; ++i) { ret += s2[i]; } ret -= 2 * dp[len1][len2]; return ret; } };