跳转至

712.Minimum ASCII Delete Sum for Two Strings

Tags: Medium Dynamic Programming

Links: https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/


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


很明显的动态规划的题目,编辑距离的变形题目,用d[i][j]代表s1的前i个字符和s2的前j个字符相同的最小代价(求删除字母的ASCII和其实就是删除的代价),状态转移方程,如果s1的第i个字符和s2的第j个字符相同,那么无需删除,直接等于d[i - 1][j - 1],如果不同,两个字符就有一个需要删除,选取删除后代价最小的一个。

初始化过程,考虑其中一个字符串为空的情况,数组d初始化为一个较大的数,表示初始无解,但是d[0][0] = 0,因为两个空字符串无需任何操作。

class Solution {
public:
    int minimumDeleteSum(string s1, string s2) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        int m = s1.size(), n = s2.size();
        vector<vector<int>> d(m + 1, vector<int>(n + 1, 0x3f));

        d[0][0] = 0;
        for (int i = 1; i <= m; ++i) d[i][0] = d[i - 1][0] + (int)s1[i - 1];
        for (int i = 1; i <= n; ++i) d[0][i] = d[0][i - 1] + (int)s2[i - 1];

        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (s1[i - 1] == s2[j - 1]) d[i][j] = d[i - 1][j - 1];
                else d[i][j] = min(d[i - 1][j] + (int)s1[i - 1], d[i][j - 1] + (int)s2[j - 1]);
            }
        }

        return d[m][n];
    }
};