前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Dynamic Programming - 72. Edit Distance

Dynamic Programming - 72. Edit Distance

作者头像
ppxai
发布2020-09-23 17:25:39
发布2020-09-23 17:25:39
46600
代码可运行
举报
文章被收录于专栏:皮皮星球皮皮星球
运行总次数:0
代码可运行

72. Edit Distance

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e')

Example 2:

Input: word1 = "intention", word2 = "execution" Output: 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u')

思路:

经典dp问题,仔细分析题目会发现,一个串转换为另一个串,无非三种情况,增加删除和替换,状态转移方程就是三者取其中最小的。思想和279、64如出一辙,都是由小算到大。

代码:

go:

代码语言:javascript
代码运行次数:0
复制
func minDistance(word1 string, word2 string) int {
    m, n := len(word1), len(word2)
    
    dp := make([][]int, m+1)
    for i := 0; i < m + 1; i++ {
        dp[i] = make([]int, n+1)
    }
    
    // initialization
    for i := 0; i < m + 1; i++ {
        dp[i][0] = i
    }
    
    for j := 0; j < n + 1; j++ {
        dp[0][j] = j
    } 
    
    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            if word1[i] == word2[j] {
                dp[i + 1][j + 1] = dp[i][j]
            } else {
                dp[i + 1][j + 1] = min(dp[i][j], min(dp[i + 1][j], dp[i][j+1])) + 1
            }
        }
    }
    
    return dp[m][n]
}

func min (i, j int) int {
    if i < j {
        return i 
    }
    return j
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年08月06日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档