您的位置:首页 > 其它

712. Minimum ASCII Delete Sum for Two Strings

2018-01-02 12:48 477 查看
本题出处

题目描述:

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

Explannation: Deleteing “s” from “sea” adds the ASCII value of “s”(115) to the sum.

Deleteing “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 the problem

Example 2:

Input: s1 = “delete”, s2 = “leet”

Output: 403

Explannation: 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].

题目大意是如样例所示。需要在通过删除字符的方法,寻找两个字符串最终相同的部分。因为最终寻找的相同部分的字符串可能有多种情况,所以题目只要求我们寻找删除字符ACSII码和最小的情况,并输出所删除字符的ACSII码和。

动态规划,使用迭代的方式。如果当前位置,两字符串的字符是相同的,则不需要删去,进入下一位置。如果不同,则有三种可能,要么删去第一个字符串的字符;要么删去第二个字符串的字符;要么将两个字符串的字符都删除。所以 代码如下。

C++ DP

class Solution {
public:
int minimumDeleteSum(string s1, string s2) {
int m = s1.size(), n = s2.size();
auto dp = new int[1001][1001];
for (int i = m-1; i >= 0; --i) {
dp[i]
= dp[i+1]
+ s1[i];
}
for (int j = n-1; j >= 0; --j) {
dp[m][j] = dp[m][j+1] + s2[j];
}
for (int i = m-1; i >= 0; i--)
for (int j = n-1; j >= 0; j--) {
if (s1[i] ==s2[j]) {
dp[i][j] = dp[i+1][j+1];
} else {
dp[i][j] = min(dp[i+1][j] + s1[i], dp[i][j+1] + s2[j]);
}
}
return dp[0][0];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: