1. 题目
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:
a) Insert a character
b) Delete a character
c) Replace a character
2. 思路
迭代递推,用数组mdi,表示对word1[0..i-1]和word2[0..j-1]的编辑距离。
则可以得到递归公式:
md[src, dst] = min{md[src, dst-1]+1, md[src-1, dst]+1, md[src-1, dst-1]+0 or 1 if [src] == [dst]}
3. 代码
class Solution {
public:
// 插入、删除、替换三种操作可以使用,要使得最后一个字符满足,可以通过三种操作来完成,剩下的递归
// md[src, dst] = min{md[src, dst-1]+1, md[src-1, dst]+1, md[src-1, dst-1]+0 or 1 if [src] == [dst]}
int minDistance(string word1, string word2) {
int l1 = word1.length() + 1;
int l2 = word2.length() + 1;
int md[l1][l2];
for (int j = 0; j < l2; j++) { md[0][j] = j; } // 插入
for (int i = 0; i < l1; i++) { md[i][0] = i; } // 删除
for (int i = 1; i < l1; i++) {
for (int j = 1; j < l2; j++) {
md[i][j] = min(min(md[i-1][j]+1, md[i][j-1]+1), md[i-1][j-1] + (word1[i-1] == word2[j-1] ? 0 : 1));
}
}
return md[l1-1][l2-1];
}
};