LeetCode 712. Minimum ASCII Delete Sum for Two Strings 解题报告(python)

712. Minimum ASCII Delete Sum for Two Strings

  1. Minimum ASCII Delete Sum for Two Strings python solution

题目描述

Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.
LeetCode 712. Minimum ASCII Delete Sum for Two Strings 解题报告(python)_第1张图片

解析

本题比较容易想到使用动态规划进行求解。
题目要求我们删除两个字符串中不同的元素,来使两个字符串变得相同。要求得删除元素ASCII之和最小。
换个角度求解,即求两个字符串最长公共元素序列ASCII码之和最大。

dp[i][j]表示s1字符串中第i个元素和s2字符串中第j个元素之间的最长相同元素序列的ASCII之和。

现在看递推公式,需要遍历dp[i][j]的每个位置,当对应位置的字符相等时,s1[i] == s2[j],因为已经匹配上了,不用删除字符。
如果s1[i] != s2[j],那么就有两种情况,我们可以删除s[i-1]的字符,或者删除s[j-1]的字符。确认二者中大的那个,才能使删除元素ASCII之和最小。
比如sea和eat,当首字符s和e失配了,那么有两种情况,要么删掉s,用ea和eat继续匹配,或者删掉e,用sea和at继续匹配

class Solution:
    def minimumDeleteSum(self, s1: str, s2: str) -> int:
        n=len(s1)
        m=len(s2)
        dp=[[0] *(m+1) for i in range (n+1)]
        for i in range(n):
            for j in range(m):
                if s1[i]==s2[j]:
                    dp[i+1][j+1]=dp[i][j]+ord(s1[i])
                else:
                    dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j])
        return sum(map(ord,s1+s2))-2*dp[n][m]

Reference

https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/discuss/247947/My-python-solution

你可能感兴趣的:(LeetCode,leetcode,python)