Java implementation LeetCode 712 minimum two strings and ASCII delete (the longest common string && ASCII value of the minimum)

Minimum two strings of ASCII 712. deleted and

Given two strings s1, s2, the two strings are equal to find the ASCII character value of the minimum required and to delete.

Example 1:

Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Delete "s" and "s" value (115) added to the sum of the "sea" in.
Delete "t" and added to the sum 116 "eat" in.
At the end of the two strings are equal, that is 115 + 116 = 231 and meet the minimum criteria.
Example 2:

Input: s1 = "delete", s2 = "leet"
Output: 403
Explanation: Delete "dee" string "delete" which becomes "let",
the 100 [d] +101 [e] +101 [e] Join sum. Delete "e" in "leet" in the 101 [e] to the summation.
At the end, the two strings are equal to "let", result is 100 + 101 + 101 + 101 = 403.
If instead the two string into a "lee" or "eet", we'll get the results of 433 or 417, more than answers.
note:

0 <s1.length, s2.length <= 1000 .
ASCII character string of all values between [97, 122].

class Solution {
    public int minimumDeleteSum(String s1, String s2) {
            int l1 = s1.length();
            int l2 = s2.length();
            char[] a1 = s1.toCharArray();
            char[] a2 = s2.toCharArray(); 
            int[][] dp = new int[l1 + 1][l2 + 1]; 
            for (int i = 0; i < l1; i++) { 
                dp[i + 1][0] = a1[i] + dp[i][0];
            }
            for (int j = 0; j < l2; j++) { 
                dp[0][j + 1] = a2[j] + dp[0][j];
            }
            //dp左面代表第一个字符串的索引,右面代表第二个字符串的索引
            for (int i = 0; i < l1; ++i) {
                for (int j = 0; j < l2; j++) {
                    if (a1[i] == a2[j]) {
                        dp[i + 1][j + 1] = dp[i][j];
                    } else {
                        dp[i + 1][j + 1] = Math.min(dp[i + 1][j] + a2[j], dp[i][j + 1] + a1[i]);
                    }
                }
            }
            return dp[l1][l2];
        }   

       
}
Released 1760 original articles · won praise 30000 + · views 3.87 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/105380750