LeetCode 712. Minimum ASCII Delete Sum for Two Strings

本文介绍了一个算法问题,即通过删除两个字符串中字符使二者相等,并使得被删除字符的ASCII值之和最小。该问题类似于编辑距离问题,但权重为ASCII值而非统一权重。文章提供了一种动态规划解决方案。

Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.

kind of like edit distance and the LC583.

now, we are not asking to delete as less characters as possible to make them equal. as a matter of fact, considering the ASCII code as a weight for this char we delete. as for LC583, the weight the each character is 1.

class Solution {
    public int minimumDeleteSum(String s1, String s2) {
        int m = s1.length();
        int n = s2.length();
        
        int[][] dp = new int[m+1][n+1];
        dp[0][0] = 0;
        for (int i = 1; i<= m; i++) {
            dp[i][0] = dp[i-1][0] + (int)s1.charAt(i - 1); //pay attention here, you write it wrong the first time, and spend a lot of time trying to figure out why. the wrong code is: dp[i][0] = (int)s1.charAt(i - 1)
        }
        for (int i = 1; i<= n; i++) {
            dp[0][i] = dp[0][i-1] + (int)s2.charAt(i - 1);
        }
        for (int i = 1; i<= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (s1.charAt(i-1) == s2.charAt(j-1)) {
                    dp[i][j] = dp[i-1][j-1];
                } else {
                    int min = Math.min(dp[i-1][j] + (int)s1.charAt(i-1), dp[i][j-1] + (int)s2.charAt(j-1));
                    dp[i][j] = Math.min(dp[i-1][j-1]+(int)s1.charAt(i-1)+(int)s2.charAt(j-1), min);
                }
            }
        }
        return dp[m][n];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值