题目
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:
- Insert a character
- Delete a character
- Replace a character
题目大意就是给出两个字符串,需要经过多少步才能从word1
变成word2
,可以用的操作为插入,删除,添加
分析
题目的本质就是让你求个两个字符串之间的编辑距离,和《算法概论》(中文版)第177页中的编辑距离一样
在这里我按照我的想法大致解释一下
假设arr[i][j]
是从从word1[0,i)
到word2[0,j)
的距离,有以下三种情况
word1[0,i)
由word1[0, i-1)
插入一个字符word2[j-1]
得到word2[0,j)
由word2[0,j-1)
插入一个字符word1[i-1
]得到word1[0,i)
有word1[0,i-1)
插入一个word1[i-1]
得到,word2[0,j)
有word2[0,j-1)
添加word2[j-1]
得到
以上三种情况对应的距离为arr[i][j] = arr[i-1][j]+1
arr[i]]j] = arr[i][j-1] + 1
arr[i][j] = arr[i-1][j-1] + (word[i-1]==word[j-1] ? 0 : 1)
代码
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size();
int n = word2.size();
int arr[m+1][n+1];
for (int i = 0; i <= m; ++i) {
arr[i][0] = i;
}
for (int j = 0; j <= n; ++j){
arr[0][j] = j;
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
int min = arr[i-1][j] + 1;
if(min > arr[i][j-1] + 1){
min = arr[i][j-1] + 1;
}
int diff = word1[i-1] == word2[j-1] ? 0 : 1;
if(min > arr[i-1][j-1] + diff){
min = arr[i-1][j-1] +diff;
}
arr[i][j] = min;
}
}
return arr[m][n];
}
};