您的位置:首页 > 运维架构

583. Delete Operation for Two Strings

2017-05-23 14:39 471 查看
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:

The length of given words won't exceed 500.
Characters in given words can only be lower-case letters.
此题可理解为寻找公共最长子序列问题,使用动态规划的方法容易解决
class Solution
{
public:
int minDistance(string word1, string word2)
{
int n1,n2;
n1=word1.size();
n2=word2.size();
int c[n1+1][n2+1];
for(int i=0;i<n1+1;i++) c[i][0]=0;
for(int i=0;i<n2+1;i++) c[0][i]=0;
for(int i=1;i<=n1;i++)
{
for(int j=1;j<=n2;j++)
{
if(word1[i-1]==word2[j-1]) c[i][j]=c[i-1][j-1]+1;
else c[i][j]=max(c[i-1][j],c[i][j-1]);
}
}
int len=0;
for(int i=1;i<=n1;i++)
{
for(int j=1;j<=n2;j++)
{
if(c[i][j]>len) len=c[i][j];
}
}
return n1-len+n2-len;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: