题目描述
给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。
示例 1:
输入: “sea”, “eat”
输出: 2
解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"
解答
本题本质上是求最长公共子序列。求出最长公共子序列的长度既可以得到答案。
r
e
s
u
l
t
=
w
o
r
d
1.
s
i
z
e
(
)
+
w
o
r
d
2.
s
i
z
e
(
)
−
2
∗
m
a
x
_
l
e
n
_
o
f
_
s
u
b
s
e
q
u
e
n
c
e
result = word1.size() + word2.size() - 2*max\_len\_of\_subsequence
result=word1.size()+word2.size()−2∗max_len_of_subsequence
最长公共子序列问题求解方法:https://blog.csdn.net/yuanliang861/article/details/89371578
class Solution {
public:
int minDistance(string word1, string word2) {
int n=word1.size(), m=word2.size();
vector<vector<int>> dp(n+1,vector<int>(m+1,0));
for(int i=1;i<n+1;++i)
{
for(int j=1;j<m+1;++j)
{
if(word1[i-1]==word2[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
return m+n-2*dp[n][m];
}
};