LeetCode 72 Edit Distance(Python详解及实现)

【题目】

Given two words word1 and word2, find theminimum number of steps required to convert word1 to word2. (each operation iscounted as 1 step.)

 

You have the following 3 operationspermitted on a word:

 

a) Insert a character

b) Delete a character

c) Replace a character

 

word1最少经过多少步可以变成word2。word1允许的操作如下:

a)插入一个字符;

b)删除一个字符;

c)替换一个字符。

比如“abc”变成“aba”只需要用"a"将最后一个字符"c"替换掉就可以。此时distance = 1

如word1[i] == word2[j],只需把word1[0至i-1]变为word2[0至j-1]。此时res[i][j] = res[i-1][j-1]

 

【思路】

l  替换:

若word1[i]替换为word2[j]是从word1到word2的最小改动,则需先把word1[0至i-1]以最小距离变为word2[0至j-1],然后在执行替换操作,此时res[i][j] = res[i-1][j-1] + 1

l  插入:

若word1[i]插入某字符为是从word1到word2的最小改动,则需先把word1[0至i-1]以最小距离变为word2[0至j-1],然后在执行插入操作,此时res[i][j] = res[i-1][j-1] + 1

l  删除:

若word1[i]删除某字符是从word1到word2的最小改动,则需先把word1[0至i-1]以最小距离变为word2[0至j-1],然后在执行插入操作,此时res[i][j] = res[i-1][j-1] + 1

 

 

【Python实现】

class Solution:

    #@return an integer

   def minDistance(self, word1, word2):

       m=len(word1)+1

       n=len(word2)+1

       dp = [[0 for i in range(n)] for j in range(m)]#(m+1)*(n+1)二维矩阵

       for i in range(n):

           dp[0][i]=i

       for i in range(m):

           dp[i][0]=i

       for i in range(1,m):

           for j in range(1,n):

                dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1, dp[i-1][j-1]+(0 if word1[i-1]==word2[j-1] else 1))

       return dp[m-1][n-1]

   

s = Solution()

s.minDistance("bird","ibdr")

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值