# LWC 55：712. Minimum ASCII Delete Sum for Two Strings

## LWC 55：712. Minimum ASCII Delete Sum for Two Strings

Problem:

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

```    public int minimumDeleteSum(String s1, String s2) {
dp = new int[s1.length() + 1][s2.length() + 1];
return go(s1.toCharArray(), s2.toCharArray(), s1.length() - 1, s2.length() - 1);
}

int[][] dp;
int go(char[] cs1, char[] cs2, int p1, int p2) {
if (dp[p1 + 1][p2 + 1] > 0) return dp[p1 + 1][p2 + 1];
if (p1 == -1 && p2 == -1) return 0;
if (p1 == -1 && p2 != -1) {
int ans = go(cs1, cs2, p1, p2 - 1);
ans += cs2[p2];
dp[0][p2 + 1] = ans;
return ans;
}
if (p1 != -1 && p2 == -1) {
int ans = go(cs1, cs2, p1 - 1, p2);
ans += cs1[p1];
dp[p1 + 1][0] = ans;
return ans;
}

if (cs1[p1] == cs2[p2]) {
int ans = go(cs1, cs2, p1 - 1, p2 - 1);
dp[p1 + 1][p2 + 1] = ans;
return ans;
}
else {
int a1 = go(cs1, cs2, p1 - 1, p2);
int a2 = go(cs1, cs2, p1, p2 - 1);
return dp[p1 + 1][p2 + 1] = Math.min(a1 + cs1[p1], a2 + cs2[p2]);
}
}```

```    public int minimumDeleteSum(String s1, String s2) {
char[] cs1 = s1.toCharArray();
char[] cs2 = s2.toCharArray();
int n1 = cs1.length;
int n2 = cs2.length;
int[][] dp = new int[n1 + 1][n2 + 1];

for (int i = 0, t = 0; i < n2; ++i) {
t += cs2[i];
dp[0][i + 1] = t;
}

for (int i = 0, t = 0; i < n1; ++i) {
t += cs1[i];
dp[i + 1][0] = t;
}

for (int i = 1; i <= n1; ++i) {
for (int j = 1; j <= n2; ++j) {
if (cs1[i - 1] == cs2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
}
else {
dp[i][j] = Math.min(dp[i][j - 1] + cs2[j - 1], dp[i - 1][j] + cs1[i - 1]);
}
}
}
return dp[n1][n2];
}  ```

0 条评论

## 相关文章

### 《剑指Offer》附加题_用两个队列实现一个栈_C++版

在《剑指Offer》中，在栈和队列习题中，作者留下来一道题目供读者自己实现，即“用两个队列实现一个栈”。 　　在计算机数据结构中，栈的特点是后进先出，即最后...

32450

23890

415100

19530

### Golang语言断言

golang中的所有程序都实现了interface{}的接口，这意味着，所有的类型如string,int,int64甚至是自定义的struct类型都就此拥有了i...

325110

20290

11810

### scala如何解决类型强转问题

scala如何解决类型强转问题 　　scala属于强类型语言，在指定变量类型时必须确定数据类型，即便scala拥有引以为傲的隐式推到，这某些场合也有些有心无力。...

36290