求兩個字符串之間的最短編輯距離,即原來的字符串至少要經過多少次操作才能夠變成目標字符串,操作包括刪除一個字符、插入一個字符、更新一個字符。
注意點:
無例子:
輸入: word1 = “heo”, word2 = “hello”
輸出: 2
又是一道典型的動態規劃。現在用dp[i][j]來表示字符串word1[:i]轉化到word2[:j]的最小編輯距離,那麼最後一次操作可能有三種情況:
在word1[:i-1]轉化為word2[:j]的基礎上再刪除word1[i] 在word1[:i]轉化為word2[:j-1]的基礎上再插入word2[j] 在word1[:i-1]轉化為word2[:j-1]的基礎上將word1[i]更新為word2[j](可能本來就相同)所以有如下遞推式:dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + onemore)
class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
m = len(word1)
n = len(word2)
dp = [[0 for __ in range(m + 1)] for __ in range(n + 1)]
for j in range(m + 1):
dp[0][j] = j
for i in range(n + 1):
dp[i][0] = i
for i in range(1, n + 1):
for j in range(1, m + 1):
onemore = 1 if word1[j - 1] != word2[i - 1] else 0
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + onemore)
return dp[n][m]
if __name__ == "__main__":
assert Solution().minDistance("", "a") == 1
assert Solution().minDistance("faf", "efef") == 2