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:
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;
}
};
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;
}
};
相关文章推荐
- 583. Delete Operation for Two Strings
- [Leetcode] 583. Delete Operation for Two Strings 解题报告
- [LeetCode] 583. Delete Operation for Two Strings
- [leetcode]583. Delete Operation for Two Strings
- leetcode 583. Delete Operation for Two Strings
- [LeetCode]583. Delete Operation for Two Strings
- [leetcode] 583. Delete Operation for Two Strings
- [LeetCode] 583. Delete Operation for Two Strings 两个字符串的删除操作
- LeetCode:M-583. Delete Operation for Two Strings
- leetcode 583. Delete Operation for Two Strings 问题转换+最长公共子串 + DP动态规划
- LeetCode - 583. Delete Operation for Two Strings
- 583. Delete Operation for Two Strings
- 583.Delete Operation for Two Strings
- 583. Delete Operation for Two Strings(两个字符串的删除操作)
- 【Leetcode】583. Delete Operation for Two Strings
- LeetCode Delete Operation for Two Strings
- [LeetCode] Delete Operation for Two Strings 两个字符串的删除操作
- Delete Operation for Two Strings
- [leetcode 583] Delete Operation for Two Strings
- 583. Delete Operation for Two Strings