leetcode 712. Minimum ASCII Delete Sum for Two Strings ( Python )

描述

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

Example 1:ios

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].
复制代码

解析

根据题意,能够看出这种求最优的问题能够用 DP 算法来解决,其实直接使用 LCS 的 ASCII 之和做为状态就好了。设 dp[i][j] 为 s1 前 i 个字符与 s2 前 j 个字符获得的 LCS 的 ASCII 和。less

转移方程是:
对于 s1[0…i−1] 和 s2[0…j−1] 的 LCS 的 ASCII 的和应该是这样的:
1. 若 s1[i−1]==s2[j−1] ,则 dp[i][j] = dp[i - 1][j - 1] + ord(s1[i - 1])
2. 若不相等,则 s1[i−1], s2[j−1] 选择删除一个,dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
复制代码

时间复杂度为 O(N^2),空间复杂度为 O(N^2)。yii

解答

class Solution(object):
def minimumDeleteSum(self, s1, s2):
    """
    :type s1: str
    :type s2: str
    :rtype: int
    """
    l1, l2 = len(s1), len(s2)
    dp = [[0] * (l2 + 1) for _ in range(l1 + 1)]
    for i in range(1, l1 + 1):
        for j in range(1, l2 + 1):
            if s1[i - 1] == s2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + ord(s1[i - 1])
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    result = sum(map(ord, s1 + s2)) - dp[-1][-1] * 2
    return result
复制代码

运行结果

Runtime: 596 ms, faster than 73.80% of Python online submissions for Minimum ASCII Delete Sum for Two Strings.
Memory Usage: 12.6 MB, less than 94.12% of Python online submissions for Minimum ASCII Delete Sum for Two Strings.
复制代码

每日格言:人生中出现的一切,都没法拥有,只能经历。svg

请做者吃橘子
支付宝

支付宝

微信

微信
相关文章
相关标签/搜索