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 与 n长度字符串需要至少新增操作n次
i <- 0 to row.length dp(i)(0) = i
j <- 0 to col.length dp(0)(j) = j
状态转换方程:
if(word1(i-1) == word2(j-1)) dp(i)(j) = math.min(math.min(dp(i)(j-1)+1, dp(i-1)(j)+1), dp(i-1)(j-1))
if(word1(i-1) != wordw(j-1)) dp(i)(j) = 1 + math.min(math.min(dp(i)(j-1), dp(i-1)(j)), dp(i-1)(j-1))
*/
object Solution {
def minDistance(word1: String, word2: String): Int = {
val word1Len = word1.length
val word2Len = word2.length
if(word1Len*word2Len == 0) return word1Len+word2Len
val dp = Array.ofDim[Int](word1Len+1, word2Len+1)
//init
for(i <- 0 to word1Len) dp(i)(0) = i
for(j <- 0 to word2Len) dp(0)(j) = j
for(i <- 1 to word1Len){
for(j <- 1 to word2Len){
if(word1(i-1) == word2(j-1)) dp(i)(j) = math.min(math.min(dp(i)(j-1)+1, dp(i-1)(j)+1), dp(i-1)(j-1))
else dp(i)(j) = 1 + math.min(math.min(dp(i)(j-1), dp(i-1)(j)), dp(i-1)(j-1))
}
}
return dp(word1Len)(word2Len)
}
}