LeetCode 712. Minimum ASCII Delete Sum for Two Strings
21 Aug 2018Description:
Given two strings s1
, s2
, find the lowest ASCII sum of deleted characters to make two strings equal.
Note:
0 < s1.length, s2.length <= 1000
.- All elements of each string will have an ASCII value in
[97, 122]
.
Example:
input:
s1 = “sea”, s2 = “eat”
output:
231
explanation:
Deleting “s” from “sea” adds the ASCII value of “s” (115) to the sum.
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.
Solution:
class Solution:
def minimumDeleteSum(self, s1, s2):
# cost[i][j] is the minimal cost for s1[0:i] and s2[0:j]
cost = [[0] * (len(s2) + 1) for _ in range(len(s1) + 1)]
# construct border
# when i or j is 0, clearly we need to delete all characters in another string
for i in range(1, len(s1) + 1):
cost[i][0] = cost[i - 1][0] + ord(s1[i - 1])
for j in range(1, len(s2) + 1):
cost[0][j] = cost[0][j - 1] + ord(s2[j - 1])
for i in range(1, len(s1) + 1):
for j in range(1, len(s2) + 1):
if s1[i - 1] == s2[j - 1]:
# if corresponding characters are equal, no deletion is needed
cost[i][j] = cost[i - 1][j - 1]
else:
cost[i][j] = min(cost[i - 1][j] + ord(s1[i - 1]), # delete character in s1
cost[i][j - 1] + ord(s2[j - 1]) # delete character in s2
)
return cost[-1][-1]
This is a dynamic programming problem. I tried to use the LCS approach, but it turns out to be inefficient because we need to enumerate all possible LCS and pick the one with greatest ASCII sum. The proper way to do it is to use DP directly to decide the minimum sum of deletion.