Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You have the following 3 operations permitted on a word:
Insert a character(插入)
Delete a character(删除)
Replace a character(代替)
Example
Given word1 = "mart" and word2 = "karma", return 3
题解1 - 双序列动态规划
两个字符串⽐较,求最值,直接看似乎并不能直接找出解决⽅案,这时往往需要使⽤动态规划的思想寻找递推关系。使⽤双序列动态规划的通⽤做法,不妨定义 f[i][j] 为字符串1的前 i 个字符和字符串2的前 j 个字符的编辑距离,那么接下来寻找其递推关系。增删操作互为逆操作,即增或者删产⽣的步数都是⼀样的。故初始化时容易知道 f[0][j] = j, f[i][0] = i , 接下来探讨 f[i][j]和 f[i - 1][j - 1] 的关系,和 LCS 问题类似,我们分两种情况讨论,即 word1[i] == word2[j]与否,第⼀种相等的情况有:
1. i == j , 且有 word1[i] == word2[j] , 则由 f[i - 1][j - 1] -> f[i][j] 不增加任何操作,有 f[i][j] = f[i -