Skip to content

Commit aed2a49

Browse files
Sync LeetCode submission Runtime - 12 ms (81.39%), Memory - 18.2 MB (65.94%)
1 parent 1eef7f6 commit aed2a49

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<p>Given two strings <code>s1</code> and&nbsp;<code>s2</code>, return <em>the lowest <strong>ASCII</strong> sum of deleted characters to make two strings equal</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> s1 = &quot;sea&quot;, s2 = &quot;eat&quot;
8+
<strong>Output:</strong> 231
9+
<strong>Explanation:</strong> Deleting &quot;s&quot; from &quot;sea&quot; adds the ASCII value of &quot;s&quot; (115) to the sum.
10+
Deleting &quot;t&quot; from &quot;eat&quot; adds 116 to the sum.
11+
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> s1 = &quot;delete&quot;, s2 = &quot;leet&quot;
18+
<strong>Output:</strong> 403
19+
<strong>Explanation:</strong> Deleting &quot;dee&quot; from &quot;delete&quot; to turn the string into &quot;let&quot;,
20+
adds 100[d] + 101[e] + 101[e] to the sum.
21+
Deleting &quot;e&quot; from &quot;leet&quot; adds 101[e] to the sum.
22+
At the end, both strings are equal to &quot;let&quot;, and the answer is 100+101+101+101 = 403.
23+
If instead we turned both strings into &quot;lee&quot; or &quot;eet&quot;, we would get answers of 433 or 417, which are higher.
24+
</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= s1.length, s2.length &lt;= 1000</code></li>
31+
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
32+
</ul>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public:
3+
int minimumDeleteSum(string s1, string s2) {
4+
int n = s1.size();
5+
int m = s2.size();
6+
7+
vector<vector<int>> dp(n+1, vector<int>(m+1, 0));
8+
for (int i=1; i<=n; i++) dp[i][0] = dp[i-1][0] + s1[i-1];
9+
for (int i=1; i<=m; i++) dp[0][i] = dp[0][i-1] + s2[i-1];
10+
11+
for (int i=1; i<=n; i++) {
12+
for (int j=1; j<=m; j++) {
13+
if (s1[i-1] == s2[j-1]) dp[i][j] = dp[i-1][j-1];
14+
else dp[i][j] = min(dp[i-1][j] + s1[i-1], dp[i][j-1] + s2[j-1]);
15+
}
16+
}
17+
18+
return dp[n][m];
19+
}
20+
};
21+

0 commit comments

Comments
 (0)