题目: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
思路:这道题目要我们求出将一个字符串转换为另一个字符串所需要的最小操作数,其中所允许的操作为插入一个字符,删除一个字符,替换一个字符。利用dp[i][j]表示word1的前i个字符转换到word2的前j个字符所需的最小操作数,状态转移方程为:dp[i][j] = min(1+dp[i-1][j], min(1+dp[i][j-1], dp[i-1][j-1] + (word1[i-1]==word2[j-1] ? 0 : 1)));其中1+dp[i-1][j]可以看成是删除一个字符,1+dp[i][j-1]可以看成是插入一个字符,dp[i-1][j-1] + (word1[i-1]==word2[j-1] ? 0 : 1))可以看成是替换一个字符。算法实现如下:
class Solution {
public:
int minDistance(string word1, string word2) {
int l1 = word1.size(), l2 = word2.size();
vector<vector<int> > dp(l1+1, vector<int>(l2+1, 0));
for (int i = 1; i <= l1; i++) dp[i][0] = i;
for (int i = 1; i <= l2; i++) dp[0][i] = i;
for (int i = 1; i <= l1; i++) {
for (int j = 1; j <= l2; j++) {
dp[i][j] = min(1+dp[i-1][j], min(1+dp[i][j-1], dp[i-1][j-1] + (word1[i-1]==word2[j-1] ? 0 : 1)));
}
}
return dp[l1][l2];
}
};