Delete Operation for Two Strings
A.题意
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.
Example 1:
Input: “sea”, “eat”
Output: 2
Explanation: You need one step to make “sea” to “ea” and another step to make “eat” to “ea”.
Note:
1.The length of given words won’t exceed 500.
2.Characters in given words can only be lower-case letters.
B.思路
其实这道题跟《算法概论》书上讲的编辑距离的题目差不多了,用动态规划的思维可以解决,我们新建一个二维数组dp[i][j]来表示扫描到word1[i - 1]和word2[j - 1]时对应的操作数,可见此时有三种情况,删去word1[i - 1]与word2的第0到j - 1位对齐,删去word2[j - 1]与word1的0到i - 1位对齐或者此时两个字符对应位置相等不用操作或者此时word1[i - 1]和word2[j - 1]不同而前面的字符串相同要同时删除两者。我们只需要遍历字符串然后取出最小的即可。
C.代码实现
class Solution {
public:
int minDistance(string word1, string word2) {
int len1 = word1.size();
int len2 = word2.size();
vector<vector<int> > dp(len1 + 1, vector<int>(len2 + 1, 0));
for (int i = 0;i <= len1;i++)
{
dp[i][0] = i;
}
for (int i = 0;i <= len2;i++)
{
dp[0][i] = i;
}
for (int i = 1;i <= len1;i++)
{
for (int j = 1;j <= len2;j++)
{
int temp = (word1[i - 1] == word2[j - 1]) ? 0 : 2;
int minnum = min(temp + dp[i - 1][j - 1],1 + dp[i - 1][j]);
minnum = min(minnum,1 + dp[i][j - 1]);
dp[i][j] = minnum;
}
}
return dp[len1][len2];
}
};