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];
}
}

本文介绍了一个算法问题,即通过删除两个字符串中字符使二者相等,并使得被删除字符的ASCII值之和最小。该问题类似于编辑距离问题,但权重为ASCII值而非统一权重。文章提供了一种动态规划解决方案。
294

被折叠的 条评论
为什么被折叠?



