[leetcode] 72.编辑距离
生活随笔
收集整理的這篇文章主要介紹了
[leetcode] 72.编辑距离
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你兩個單詞?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')
提示:
- 0 <= word1.length, word2.length <= 500
- word1?和?word2?由小寫英文字母組成
動態規劃
class Solution:def minDistance(self, word1: str, word2: str) -> int:n = len(word1)m = len(word2)#有一個字符串為空串if n*m == 0:return n+m #DP二維數組,DP[n+1][m+1]:DP[i][j]表示word1[0...i]替換為word2[0...j]的最小操作次數DP = [[0]*(m+1) for _ in range(n+1)]#邊界狀態初始化for i in range(n+1):DP[i][0] = i for j in range(m+1):DP[0][j] = j#計算所有DP值for i in range(1,n+1):for j in range(1,m+1):if word1[i-1]==word2[j-1]:DP[i][j]=DP[i-1][j-1]if word1[i-1]!=word2[j-1]:DP[i][j] = min(DP[i-1][j-1],#替換DP[i-1][j],#刪除DP[i][j-1])+1 #插入操作return DP[n][m]總結
以上是生活随笔為你收集整理的[leetcode] 72.编辑距离的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [leetcode]236.二叉树的最近
- 下一篇: [leetcode] 912.排序数组