《LeetCode筆記98》 編輯距離

2021-10-09 08:28:59 字數 1576 閱讀 6228

給你兩個單詞 word1 和 word2,請你計算出將 word1 轉換成 word2 所使用的最少運算元 。

你可以對乙個單詞進行如下三種操作:

插入乙個字元

刪除乙個字元

替換乙個字元

示例 1:

輸入:word1 = "horse", word2 = "ros"

輸出:3

解釋:horse -> rorse (將 'h' 替換為 'r')

rorse -> rose (刪除 'r')

rose -> ros (刪除 'e')

示例 2:

輸入:word1 = "intention", word2 = "execution"

輸出:5

解釋:intention -> inention (刪除 't')

inention -> enention (將 'i' 替換為 'e')

enention -> exention (將 'n' 替換為 'x')

exention -> exection (將 'n' 替換為 'c')

exection -> execution (插入 'u')

動態規劃

class solution:

def mindistance(self, word1: str, word2: str) -> int:

l1 = len(word1)

l2 = len(word2)

self.dp = [[0] * (l2+1) for i in range(l1+1)]

result = self.distance(word1, word2)

return result

def distance(self, word1, word2):

l1 = len(word1)

l2 = len(word2)

if l1==0:

return l2

elif l2==0:

return l1

elif self.dp[l1][l2]!=0:

return self.dp[l1][l2]

elif word1[-1]==word2[-1]:

self.dp[l1][l2] = min(self.distance(word1[:-1], word2[:-1]),

self.distance(word1[:-1], word2)+1,

self.distance(word1, word2[:-1])+1)

elif word1[-1]!=word2[-1]:

self.dp[l1][l2] = min(self.distance(word1[:-1], word2[:-1])+1,

self.distance(word1[:-1], word2)+1,

self.distance(word1, word2[:-1])+1)

return self.dp[l1][l2]

standford NLP課程筆記四 編輯距離

編輯距離用來衡量兩個串的相似度 編輯距離就是用最少的編輯操作將乙個詞變為另乙個詞,操作有三種 插入刪除 替換如何計算最短編輯距離?採用動態規劃 字串x長度為n 字串y長度為m 定義d i,j 表示x 1,i 和y 1,j 的最短編輯距離,則d n,m 表示x和y的最短編輯距離,注意這裡的字串 下標是...

動態規劃之LeetCode第72題 編輯距離

首先先學習乙個經典的演算法吧,就是和本題一模一樣的 編輯距離演算法 編輯距離,minimum edit distance,簡稱med,是俄羅斯科學家 vladimir levenshtein 在1965年提出,也因此而得名 levenshtein distance。用來度量兩個序列相似程度的指標。通...

解題思路 leetcode第七十二題 編輯距離

題目描述 給你兩個單詞 word1 和 word2,請你計算出將 word1 轉換成 word2 所使用的最少運算元 你可以對乙個單詞進行如下三種操作 插入乙個字元 刪除乙個字元 替換乙個字元 示例 1 輸入 word1 horse word2 ros 輸出 3 解釋 horse rorse 將 h...