问题描述
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
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
分析
用动态规划求解
dp(i,j)表示对于word1前i个字符和word2前j个字符,需要的最少操作次数。
当word1[i-1]==word2[j-1],dp(i,j)=dp(i-1,j-1)
当word1[i-1]!=word2[j-1],就要根据操作的不同分情况求解,取三者之间的最小值。
注意:这里是 word1[i-1]和word2[j-1] 的比较,而不是word1[i],word2[j]。在提交代码的时候我就是没搞清楚这里的对应的关系,报错了。dp[0][0]两个空字符串的距离,肯定为0。dp的维度为len1+1,len2+1。
当选择替换操作时,word1[i]=word2[j],dp(i,j)=dp(i-1,j-1)+1
当选择删除操作时,dp(i,j)=dp(i-1,j)+1
当选择插入操作时,word1[i]=word2[j],word1[i+1]=word1[i]....;dp(i,j)=dp(i,j-1)+1
对于我来说,第三个不好想。插入这个操作会使word1的长度增加,但是在处理时,可以想成插入的那个字符和word2[j]由于相同会被抵消掉。
举例:
horse 和hos
dp[3,3]是在计算hor和hos的距离
如果选择插入,则变成ho(s)r和hos,注意此时r依然是第一个词的第三个字符,总距离也就是hor和ho的距离dp(i,j-1)加1
同理,如果选择删除,则变成ho和hos,总距离就是ho和hos的距离dp(i-1,j)加1
最后考虑一下边界和初始条件:
当第一个字符串为空时,第二个字符串长度为几,就要进行几个插入操作。
当第二个字符串为空时,第一个字符串长度为几,就要进行几个删除操作。
初始条件和边界很类似。
代码
class Solution {
public:
int minDistance(string word1, string word2) {
int len1=word1.length();
int len2=word2.length();
if(len1<=0)
return len2;
if(len2<=0)
return len1;
int dp[len1+1][len2+1];
for(int i=0;i<=len1;i++)
{
dp[i][0]=i;
}
for(int j=1;j<=len2;j++)
{
dp[0][j]=j;
}
for(int i=1;i<=len1;i++)
for(int j=1;j<=len2;j++)
{
if(word1[i-1]==word2[j-1])
dp[i][j]=dp[i-1][j-1];
else
dp[i][j]=min(min(dp[i][j-1],dp[i-1][j]),dp[i-1][j-1])+1;
}
return dp[len1][len2];
}
};