给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。
示例 1:
输入: "sea", "eat"
输出: 2
解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"
说明:
给定单词的长度不超过500。
给定单词中的字符只含有小写字母。
C++
class Solution {
public:
int minDistance(string word1, string word2)
{
int m=word1.length();
int n=word2.length();
vector<vector<int>> tmp(m+1,vector<int>(n+1,0));
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(word1[i-1]==word2[j-1])
{
tmp[i][j]=tmp[i-1][j-1]+1;
}
else
{
tmp[i][j]=max(tmp[i-1][j],tmp[i][j-1]);
}
}
}
return m+n-2*tmp[m][n];
}
};
python
class Solution:
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
m=len(word1)
n=len(word2)
tmp=[[0 for j in range(n+1)] for i in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if word1[i-1]==word2[j-1]:
tmp[i][j]=tmp[i-1][j-1]+1
else:
tmp[i][j]=max(tmp[i-1][j],tmp[i][j-1])
return m+n-2*tmp[m][n]