712 Minimum ASCII Delete Sum for Two Strings

712 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.
  • 题目大意:给定两个字符串,求删除的最小字符的ASCII和,使两个字符串相等。

  • 思路:dp,dp[i][j]表示从当前位置开始,两个字符串删除得到最小的ASCii和使两个字符串相等,转移关系式

    dp[i][j] = a[i] == b[j] ? dp[i + 1][j + 1] : min(a[i] + dp[i + 1][j],  // 删除 a[i] + minimumDeleteSum(a.substr(i+1), b.substr(j))
     b[j] + dp[i][j + 1])  // 删除 b[j] + minimumDeleteSum(a.substr(i), b.substr(j+1))
  • 代码:

    package DP;
    
    /**
     * @Author OovEver
     * @Date 2017/12/15 9:17
     */
    public class LeetCode712 {
        public int minimumDeleteSum(String s1, String s2) {
            int m = s1.length(), n = s2.length();
            int max = Integer.MAX_VALUE;
            char[] a = s1.toCharArray();
            char[] b = s2.toCharArray();
    //        dp[i][j]表示从当前位置开始,两个字符串删除得到最小的ASCii和使两个字符串相等
            int[][] dp = new int[m + 1][n + 1];
            for(int i=m;i>=0;i--) {
                for(int j=n;j>=0;j--) {
                    if (i < m || j < n) {
                        dp[i][j] = i < m && j < n && a[i] == b[j] ? dp[i + 1][j + 1] : Math.min((i < m ? a[i] + dp[i + 1][j] : max), j < n ? b[j] + dp[i][j + 1] : max);
                    }
                }
            }
            return dp[0][0];
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值