712. Minimum ASCII Delete Sum for Two Strings(动态规划)

1. Description

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”,adds100[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.


2. Analysis

这道题其实是关于寻找最长公共子序列的变体,题目要求的是被剔除的字符的最小ASCII码总和,把问题倒过来看,在保证最长子序列的基础上,寻找这个最小ACSII码总和,如此一来,只需要修改一下求救最长子序列的程序就能找出来。

而最长子序列的情况无非以下三种:

  1. Si+1=Ti+1 时,在 S1...Si T1...Ti 的公共子序列末尾加上 Si+1
  2. S1...Si+1 T1...Ti 的公共自序列
  3. S1...Si T1...Ti+1 的公共子序列

得到求解最长子序列长度的状态转移方程为:

dp[i+1][j+1]=max(dp[i][j]+1,dp[i][j+1],dp[i+1][j]),max(dp[i][j+1],dp[i+1][j])Si+1 = Tj+1


3. Code

#include<iostream>
#include<string.h>
#include<string>
using namespace std;

int max(int a, int b) {
    return a>b? a:b;
}
int minimumDeleteSum(string s1, string s2) {
    string res = "";
    int dp[s1.length()+1][s2.length()+1];
    memset(dp, 0, sizeof(dp));
    int sum = 0;
    //find the longest common sub sequence between s1 and s2
    // find the total ASCII value of the subString
    // if the value is largest, delete sum will be lowest
    for(int i = 0; i < s1.length(); i++) {
        sum += (int)s1[i];
        for(int j = 0; j < s2.length(); 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]);
            }
        }
    }

    for(int j = 0; j < s2.length();j ++) {
        sum += (int)s2[j];
    }

    return sum - 2*dp[s1.length()][s2.length()];   
}

int main() {
    string s1 = "delete";
    int sum = 0;
    cout << minimumDeleteSum(s1,"leet") <<endl;
    for(int i=0; i < s1.length(); i++) {
        cout << (int)s1[i] << endl;
        sum += (int)s1[i];
    }
    cout << sum <<endl;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值