Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.php
Example 1:ios
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].
複製代碼
根據題意,能夠看出這種求最優的問題能夠用 DP 算法來解決,其實直接使用 LCS 的 ASCII 之和做爲狀態就好了。設 dp[i][j] 爲 s1 前 i 個字符與 s2 前 j 個字符獲得的 LCS 的 ASCII 和。less
轉移方程是:
對於 s1[0…i−1] 和 s2[0…j−1] 的 LCS 的 ASCII 的和應該是這樣的:
1. 若 s1[i−1]==s2[j−1] ,則 dp[i][j] = dp[i - 1][j - 1] + ord(s1[i - 1])
2. 若不相等,則 s1[i−1], s2[j−1] 選擇刪除一個,dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
複製代碼
時間複雜度爲 O(N^2),空間複雜度爲 O(N^2)。yii
class Solution(object):
def minimumDeleteSum(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: int
"""
l1, l2 = len(s1), len(s2)
dp = [[0] * (l2 + 1) for _ in range(l1 + 1)]
for i in range(1, l1 + 1):
for j in range(1, l2 + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + ord(s1[i - 1])
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
result = sum(map(ord, s1 + s2)) - dp[-1][-1] * 2
return result
複製代碼
Runtime: 596 ms, faster than 73.80% of Python online submissions for Minimum ASCII Delete Sum for Two Strings.
Memory Usage: 12.6 MB, less than 94.12% of Python online submissions for Minimum ASCII Delete Sum for Two Strings.
複製代碼
每日格言:人生中出現的一切,都沒法擁有,只能經歷。svg