Skip to content

Commit b460f35

Browse files
committed
feat: finish 712
1 parent d765162 commit b460f35

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# 712. Minimum ASCII Delete Sum for Two Strings
2+
3+
- Difficulty: Medium.
4+
- Related Topics: String, Dynamic Programming.
5+
- Similar Questions: Edit Distance, Longest Increasing Subsequence, Delete Operation for Two Strings.
6+
7+
## Problem
8+
9+
Given two strings ```s1``` and ```s2```, return **the lowest **ASCII** sum of deleted characters to make two strings equal**.
10+
11+
 
12+
Example 1:
13+
14+
```
15+
Input: s1 = "sea", s2 = "eat"
16+
Output: 231
17+
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
18+
Deleting "t" from "eat" adds 116 to the sum.
19+
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
20+
```
21+
22+
Example 2:
23+
24+
```
25+
Input: s1 = "delete", s2 = "leet"
26+
Output: 403
27+
Explanation: Deleting "dee" from "delete" to turn the string into "let",
28+
adds 100[d] + 101[e] + 101[e] to the sum.
29+
Deleting "e" from "leet" adds 101[e] to the sum.
30+
At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.
31+
If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.
32+
```
33+
34+
 
35+
**Constraints:**
36+
37+
38+
39+
- ```1 <= s1.length, s2.length <= 1000```
40+
41+
- ```s1``` and ```s2``` consist of lowercase English letters.
42+
43+
44+
45+
## Solution
46+
47+
```javascript
48+
/**
49+
* @param {string} s1
50+
* @param {string} s2
51+
* @return {number}
52+
*/
53+
var minimumDeleteSum = function(s1, s2) {
54+
var map = {};
55+
var dfs = function(i, j) {
56+
var key = i + ',' + j;
57+
if (map[key]) return map[key];
58+
if (!s1[i] && !s2[j]) return 0;
59+
if (!s1[i]) return map[key] = s2.slice(j).split('').reduce((sum, s) => sum + s.charCodeAt(0), 0);
60+
if (!s2[j]) return map[key] = s1.slice(i).split('').reduce((sum, s) => sum + s.charCodeAt(0), 0);
61+
if (s1[i] === s2[j]) return map[key] = dfs(i + 1, j + 1);
62+
return map[key] = Math.min(
63+
dfs(i + 1, j) + s1.charCodeAt(i),
64+
dfs(i, j + 1) + s2.charCodeAt(j),
65+
);
66+
};
67+
return dfs(0, 0);
68+
};
69+
```
70+
71+
**Explain:**
72+
73+
For every [i, j] in [s1, s2], you could delete a char from s1[i] or s2[j], that end up with two possible ways.
74+
75+
76+
Top down to search and summarize, use map to memorize the result of every path we tried.
77+
78+
79+
We could also go bottom up, that's the reverse version of it, try it yourself!
80+
81+
**Complexity:**
82+
83+
* Time complexity : O(m * n).
84+
* Space complexity : O(m * n).

0 commit comments

Comments
 (0)