File tree Expand file tree Collapse file tree
LeetCode/0712-minimum-ascii-delete-sum-for-two-strings Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ <p >Given two strings <code >s1</code > and  ; <code >s2</code >, return <em >the lowest <strong >ASCII</strong > sum of deleted characters to make two strings equal</em >.</p >
2+
3+ <p >  ; </p >
4+ <p ><strong class =" example " >Example 1:</strong ></p >
5+
6+ <pre >
7+ <strong >Input:</strong > s1 = " ; sea" ; , s2 = " ; eat" ;
8+ <strong >Output:</strong > 231
9+ <strong >Explanation:</strong > Deleting " ; s" ; from " ; sea" ; adds the ASCII value of " ; s" ; (115) to the sum.
10+ Deleting " ; t" ; from " ; eat" ; 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 = " ; delete" ; , s2 = " ; leet" ;
18+ <strong >Output:</strong > 403
19+ <strong >Explanation:</strong > Deleting " ; dee" ; from " ; delete" ; to turn the string into " ; let" ; ,
20+ adds 100[d] + 101[e] + 101[e] to the sum.
21+ Deleting " ; e" ; from " ; leet" ; adds 101[e] to the sum.
22+ At the end, both strings are equal to " ; let" ; , and the answer is 100+101+101+101 = 403.
23+ If instead we turned both strings into " ; lee" ; or " ; eet" ; , we would get answers of 433 or 417, which are higher.
24+ </pre >
25+
26+ <p >  ; </p >
27+ <p ><strong >Constraints:</strong ></p >
28+
29+ <ul >
30+ <li><code>1 <= s1.length, s2.length <= 1000</code></li>
31+ <li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
32+ </ul >
Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments