题目描述
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
解题思路
1)dp[i][j]:word1 0~i 和 word2 0~j 的编辑距离。
2)考虑word1[i] word2[j]的对齐方式:
注意因为出现 i-1,j-1,所以要考虑数组越界问题,因此多生成0行和0列,对应某一个str为空时的情况
代码如下
class Solution {
public:
int minDistance(string word1, string word2) {
if (word1.empty() && word2.empty())
return 0;
if (word1.empty())
return word2.size();
if (word2.empty())
return word1.size();
vector<int> tmp(word2.size()+1, 0);
vector<vector<int> > dp(word1.size()+1, tmp);
for (int i = 0; i <= word2.size(); i++)
dp[0][i] = i;
for (int j = 0; j <= word1.size(); j++)
dp[j][0] = j;
for (int i = 1; i <= word1.size(); i++) {
for (int j = 1; j <= word2.size(); j++) {
int op = (word1[i-1] == word2[j-1] )? dp[i - 1][j - 1] : dp[i - 1][j - 1] + 1;
dp[i][j] = fmin(dp[i - 1][j] + 1, fmin(dp[i][j - 1] + 1, op));
}
}
return dp[word1.size()][word2.size()];
}
};