weekly contest 55 第二题Minimum ASCII Delete Sum for Two Strings

来源:互联网 发布:如何查看淘宝等级 编辑:程序博客网 时间:2024/04/19 14:30

题目


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: 231Explanation: 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: 403Explanation: 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.

分析


受到之前一道题目删除的题目误导,这题我一开始的思路是找到字典顺序最大的LCS,后来超时。今天重新写的过了

还是和以前一样

先定义状态

因为要考虑空的情况因此我们

定义dp[i,j] 为 从s1[i-1] 到s2[j-1]的最小删除

接着定义初时状态这里举个例子

       d    e   l   e   t   e    0  d   d+e d+e+l ...  l l  e l+e  e l+e+e  t ...

这里我们就定义好了初时状态

接着就是状态转移方程
if( s1[i-1] == s2[j-1] )
dp[i][j] = dp[i-1][j-1] ( 这个点相等,那么我们把他们对应的去掉正好是dp[i-1][j-1])
else
不相等的话 对于dp[i][j]而言,我们要么从dp[i-1][j] + s[i-1] 到dp[i][j]要么从dp[i][j-1]到dp[i][j]
dp[i][j] = min ( dp[i-1][j] +s[i-1] , dp[i][j-1] + s2[j-1] )


代码


class Solution {public:    int minimumDeleteSum(string s1, string s2) {        int n = s1.size() ;         int m = s2.size() ;        vector< vector< int> > dp ;        dp.resize( n+1 , vector<int>( m+1, 0 ) ) ;        dp[0][0] = 0 ;        for( int i=1 ; i<=n ; i++)            dp[i][0] = s1[i-1] + dp[i-1][0];        for( int i=1 ; i<=m ; i++)            dp[0][i] = s2[i-1] + dp[0][i-1];        for( int i=1 ; i<=n ; i++){            for( int j = 1 ; j<=m ; j++){                if( s1[i-1] != s2[j-1] )                    dp[i][j] = min ( dp[i-1][j] + s1[i-1] , dp[i][j-1] + s2[j-1] );                 else                    dp[i][j] = dp[i-1][j-1];            }        }        return dp[n][m];    }};

时间复杂度
O(NM)

空间复杂度
O(NM)