首页 > 编程语言 >代码随想录算法训练营第五十五天 | 583. 两个字符串的删除操作, 72. 编辑距离

代码随想录算法训练营第五十五天 | 583. 两个字符串的删除操作, 72. 编辑距离

时间:2024-03-25 10:56:29浏览次数:28  
标签:第五十五 583 ++ res 随想录 len word1 word2 dp

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 由小写英文字母组成

 


package main

 

func minDistance(word1 string, word2 string) int { //dp[i][j] word1的i索引, word2的j索引 编辑的距离次数 //地推公式 word1[i] == words[2] dp[i][j] = dp[i-1][j-1] else dp[i][j] = max(1+dp[i-1][j-1],1+dp[i-1][j],1+dp[i][j-1]) //行初始化 0~n 初始化, 列 0~n 初始化 //上到下,左到右 //输出最后一个点 dp := make([][]int, len(word1)+1) fori := 0; i < len(dp); i++ { dp[i] = make([]int, len(word2)+1) } fori := 0; i < len(word1)+1; i++ { dp[i][0] = i } fori := 0; i < len(word2)+1; i++ { dp[0][i] = i } fori := 1; i < len(word1)+1; i++ { forj := 1; j < len(word2)+1; j++ { if word1[i-1] == word2[j-1] { dp[i][j] = dp[i-1][j-1] } else { dp[i][j] = min(1+dp[i-1][j-1], 1+dp[i][j-1], 1+dp[i-1][j]) } } } return dp[len(word1)][len(word2)] }

 

func min(a, b, c int) int { res := a if res > b { res = b } if res > c { res = c } return res }

 


583. 两个字符串的删除操作

  已解答 中等  

相关标签

相关企业  

给定两个单词 word1 和 word2 ,返回使得 word1 和 word2 相同所需的最小步数

每步 可以删除任意一个字符串中的一个字符。

 

示例 1:

输入: word1 = "sea", word2 = "eat"
输出: 2
解释: 第一步将 "sea" 变为 "ea" ,第二步将 "eat "变为 "ea"

示例 2:

输入:word1 = "leetcode", word2 = "etco"
输出:4

 

提示:

  • 1 <= word1.length, word2.length <= 500
  • word1 和 word2 只包含小写英文字母

 


func minDistance(word1 string, word2 string) int { //dp[i][j] = work[1] word[2 的最小相同步数 //递推公式 if word1[i] == word2[j] : dp[i][j] = dp[i-1][j-1] else max(2+dp[i-1][j-1],1+dp[i-1][j],1+dp[i][j-1]) //初始化 0->n 行, 0->m列 //从上到下,从左到右 //输出最后一个数 dp := make([][]int, len(word2)+1) for i := 0; i < len(dp); i++ { dp[i] = make([]int, len(word1)+1) } for i := 0; i < len(word1)+1; i++ { dp[0][i] = i } for i := 0; i < len(word2)+1; i++ { dp[i][0] = i } for i := 1; i < len(word2)+1; i++ { for j := 1; j < len(word1)+1; j++ { if word1[j-1] == word2[i-1] { dp[i][j] = dp[i-1][j-1] }else { dp[i][j] = min(dp[i-1][j-1]+2, dp[i-1][j]+1, dp[i][j-1]+1) } } } return dp[len(word2)][len(word1)] } func min(a, b, c int) int { res := a if b < a { res = b } if c < res { res = c }

标签:第五十五,583,++,res,随想录,len,word1,word2,dp
From: https://www.cnblogs.com/suxinmian/p/18093920

相关文章