题目:
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个元素达到相同需要的最小操作数。
递推: 当 word1[i]==word2[j]时,没有增加操作数,故 dp[i][j]=dp[i-1][j-1];
当 word1[i]!=word2[j]时,dp[i][j] 可以由三种状态转移成 :
(1)dp[i-1][j-1]+一个操作修改i或j的元素。
(2)dp[i][j-1]+一个操作增加j元素。
(3)dp[i-1][j]+一个操作增加i元素。
故 dp[i][j]=min(dp[i-1][j-1]+1,min(dp[i][j-1],dp[i-1][j])+1)。
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>> dp;
int i,j,l1=word1.size(),l2=word2.size();
dp.resize(l1+1);
for(i=0;i<=l1;++i)dp[i].resize(l2+1);
for(i=0;i<=l1;++i)
{
for(j=0;j<=l2;++j)
{
if(i==0)dp[i][j]=j;
else if(j==0)dp[i][j]=i;
else
{
if(word1[i-1]==word2[j-1]) dp[i][j]=dp[i-1][j-1];
else dp[i][j]=min(dp[i-1][j-1]+1,min(dp[i][j-1],dp[i-1][j])+1);
}
}
}
return dp[l1][l2];
}
};