LeetCode 712. 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.
kind of like edit distance and the LC583.
now, we are not asking to delete as less characters as possible to make them equal. as a matter of fact, considering the ASCII code as a weight for this char we delete. as for LC583, the weight the each character is 1.
class Solution {
public int minimumDeleteSum(String s1, String s2) {
int m = s1.length();
int n = s2.length();
int[][] dp = new int[m+1][n+1];
dp[0][0] = 0;
for (int i = 1; i<= m; i++) {
dp[i][0] = dp[i-1][0] + (int)s1.charAt(i - 1); //pay attention here, you write it wrong the first time, and spend a lot of time trying to figure out why. the wrong code is: dp[i][0] = (int)s1.charAt(i - 1)
}
for (int i = 1; i<= n; i++) {
dp[0][i] = dp[0][i-1] + (int)s2.charAt(i - 1);
}
for (int i = 1; i<= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1.charAt(i-1) == s2.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1];
} else {
int min = Math.min(dp[i-1][j] + (int)s1.charAt(i-1), dp[i][j-1] + (int)s2.charAt(j-1));
dp[i][j] = Math.min(dp[i-1][j-1]+(int)s1.charAt(i-1)+(int)s2.charAt(j-1), min);
}
}
}
return dp[m][n];
}
}

浙公网安备 33010602011771号