[leetcode] 712. Minimum ASCII Delete Sum for Two Strings

Question:

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

Solution:

这道题就是编辑距离问题,不同的是,只可以删除。因此,用cost[i][j] 表示把字符串s1[1, i]和s2[1, j]弄成相同字符串的代价。初始化时,
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[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]))
也即要将s1[1, i]和s2[1, j]弄成完全相同,要么是把其中一个字符串最后一个字母(s1[i]或s2[j])删掉,要么是相同的时候直接等于cost[i-1][j-1]
最后只要返回cost[s1.size()][s2.size()] 即可。
时间复杂度:O(mn)
空间复杂度:O(mn)

class Solution {
public:
    int minimumDeleteSum(string s1, string s2) {
        int cost[s1.size()+1][s2.size()+1];

        // cost[0][0] ... cost[0][j]
        cost[0][0] = 0;
        for (int i = 0; i < s2.size(); i++) {
            cost[0][i+1] = cost[0][i] + s2[i];
        }

        // cost[1][0] ... cost[i][0]
        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++) {
            cost[0][i+1] = cost[0][i] + s2[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()];
    }

    int diff(char ch1, char ch2) {
        if (ch1 == ch2)
            return 0;
        else 
            return (ch1 + ch2);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值