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

本文探讨了如何通过删除特定字符使两个字符串相等,并使被删除字符的ASCII值之和最小。利用动态规划方法,通过计算最长公共子序列的ASCII值之和来找到最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • descrption
    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码的值的最小和,那么反向思考也是求得剩下字符的ASCII码的和的最大值,因为字符串中字符的总的ASCII码值的总和是不变的。下面就可以将问题转化为:求得两个字符串中公共子序列的最大的ASCII码值的和,对求最长公共子序列的方法稍加改变就可得到该问题的答案。
求解最长子序列的状态转移方程为:
用l[i][j]记录以s1[i]和s2[j]结尾的最长子序列的长度
if s1[i] == s2[j]
l[i][j] = l[i-1][j-1] + 1;
else 
l[i][j] = max(l[i-1][j], l[i][j-1]);

==========================================================
求解该问题的状态转移方程为:
用dp[i][j]记录以s1[i]和s2[j]结尾的子序列的最大的ASCII码值的总和

if s1[i] == s2[j]
dp[i][j] = dp[i-1][j-1] + (int)s1[i]; 
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
  • 代码如下
class Solution {
public:
    int minimumDeleteSum(string s1, string s2) {
        int len1 = s1.length();
        int len2 = s2.length();
        int dp[len1+1][len2+1];
        memset(dp, 0, sizeof(dp));
        for (int i = 0; i < len1; i++) {
            for (int j = 0; j < len2; j++){
                if(s1[i] == s2[j]) {
                    dp[i+1][j+1] = dp[i][j] + (int)s1[i]; 
                }
                else {
                    dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);
                }
            }
        }

        int all = 0;
        for(int i = 0; i < len1; i ++) {
            all += (int)s1[i];
        }
        for(int j = 0; j < len2; j ++) {
            all += (int)s2[j];
        }

        return all - 2*dp[len1][len2];
    }
};

原题地址

如有错误请指出,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值