LeetCode#712 Minimum ASCII Delete Sum for Two Strings (week10)

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值