题目:
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
题意:
给定两个字符串,找到字符串A变换到字符串B的最少步骤。
对一个字符串我们有三种操作,第一是插入一个字符,第二是删除一个字符,第三是改变一个字符。
思路:
我们选取A的前i个字符变换到B的前j个字符。如果i==0,那么必须插入j个字符,同理如果j==0的话,那么A字符串删除j个可以使两者变成前j个相等。如果i,j不等于0的话,那么有三种方式,已经知道A的前i-1个字符到j的方法,那么在A中增加一个字符;如果已经知道A的前i-1个字符到达B的方法,那么删除A的第i个字符。如果知道A的前i-1个字符转换到B的前j-1个字符的步骤,那么我们可以通过更换A的第i个字符变成B的第j个字符。如果A的第i个字符跟B的第j个字符相等的话,那么只需要知道A的前i-1个字符变换到B的前j-1个字符的步骤即可。
转移方程是:
- DP[i][j] = min(DP[i-1][j-1],min(DP[i-1][j],D[i][j-1])) +1
- if(A[i-1] == B[j-1]) DP[i][j] = min(DP[i][j], DP[i-1][j-1])
以上。
代码如下:
class Solution {
public:
int minDistance(string word1, string word2) {
if (word1.empty() || word2.empty())return (word1.empty()? word2.length() : word1.length());
int len1 = word1.length();
int len2 = word2.length();
vector<vector<int>> DP(len1 + 1, vector<int>(len2 + 1, 0));
for (int i = 0; i <= len1; i++)
for (int j = 0; j <= len2; j++) {
if (i == 0 || j == 0)DP[i][j] = ((i == 0) ? j : i);
if (i != 0 && j != 0) {
DP[i][j] = min(DP[i-1][j-1],min(DP[i - 1][j], DP[i][j - 1])) + 1;
if(word1[i - 1] == word2[j - 1])DP[i][j] = min(DP[i][j], DP[i - 1][j - 1]);
}
}
return DP[len1][len2];
}
};