[leetcode] 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.

Note:

  • 0 < s1.length, s2.length <= 1000.
  • All elements of each string will have an ASCII value in [97, 122].

分析:题目要求翻译一下:给两个字符串s1、s2,要求删除这两个字符串中的一些元素,最后两个字符串相同,求删除这些元素最小的ASCII之和。有点像求两个字符串的公共字串问题,对于这种字符串+极值的题,首要考虑使用DP
1、维持一个二维数组dp(这里用二维数组的原因是有两个字符串,反正先想到的就是一个二维数组);
2、然后我们去考虑这个dp[i][j]含义,根据题目意思,很容易想到dp[i][j]代表使得s1的前i个字符与s2的前j个字符相等需要最少的ASCII之和。
3、dp数组边界的初始化,即dp[0][j]和dp[j][0]的生成,这里意思就是用一个空字符串与领域给作比较,也就是另一个字符串要删除多少个字符才能变成空字符串。
4、状态转移方程,这里也很容易想到有两种情况。第一种当前位置字符相等,s1[i-1]==s2[j-1]时,dp[i][j]=dp[i-1][j-1];第二种如果不相等,这时就考虑删除字符了,这里产生两种情况,删除s1的还是删除s2的。我们可以删除s1[i-1]的字符,且加上被删除的字符的ASCII码到上一个状态的dp值中,即dp[i-1][j] + s1[i-1],或者删除s2[j-1]的字符,且加上被删除的字符的ASCII码到上一个状态的dp值中,即dp[i][j-1] + s2[j-1]。
代码整理如下:
 1 class Solution {
 2     public int minimumDeleteSum(String s1, String s2) {
 3         int[][] dp = new int[s1.length()+1][s2.length()+1];
 4         
 5         //先把边界值确定
 6         for ( int j = 1 ; j <= s2.length() ; j ++ ){
 7             dp[0][j] = dp[0][j-1] + s2.codePointAt(j-1);
 8         }
 9         for ( int i = 1 ; i <= s1.length() ; i ++ ){
10             dp[i][0] = dp[i-1][0] + s1.codePointAt(i-1);
11         }
12 
13         //判断s1[0:i]想要和s2[0:j]相同,需要删掉字符的最小ASCII之和
14         for ( int i = 1 ; i <= s1.length() ; i ++ ){
15             for ( int j = 1 ; j <= s2.length() ; j ++ ){
16                 if ( s1.charAt(i-1) == s2.charAt(j-1) ) dp[i][j] = dp[i-1][j-1];
17                 else dp[i][j] = Math.min( dp[i][j-1] + s2.codePointAt(j-1), dp[i-1][j] + s1.codePointAt(i-1) );
18             }
19         }
20         return dp[s1.length()][s2.length()];
21     }
22 }

      运行时间25ms,超过95.87%的提交。

      类似的题目还有:[leetcode] Delete Operation for Two Strings
                                   [leetcode] Maximum Length of Repeated Subarray
                                   [leetcode] Longest Increasing Subsequence
 
posted @ 2018-07-17 16:39  Lin.B  阅读(100)  评论(0编辑  收藏  举报