# [LeetCode] Delete Operation for Two Strings 两个字符串的删除操作

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:

1. The length of given words won’t exceed 500.
2. Characters in given words can only be lower-case letters.

``````class Solution {
//这道题转换为求最大共同子序列的问题
public int minDistance(String word1, String word2) {
int m = word1.length(), n = word2.length();
//dp表示的是word1前i个字符  和  word2前j个字符中相等子序列的最大长度
//这里的dp[0][0]就是0了 当都为空的时候默认公共长度就是0
int[][] dp = new int[m+1][n+1];
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(word1.charAt(i - 1) == word2.charAt(j - 1))
//如果i j处相等 长度等于之前的+1
dp[i][j] = dp[i-1][j-1] + 1;
else
// 如果不等，那么难道我们直接将dp[i-1][j-1]赋值给dp[i][j]吗，

那么我们考虑的范围可以是abcd  abc相比较 或者 abc abc相比较
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
return (m + n) - 2 * dp[m][n];
}
}``````

``````class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length(), n = word2.length();
int[][] dp = new int[m+1][n+1];
for(int i = 1; i <= m; i++){
for(int j = 1;j <= n; j++){
if(word1.charAt(i-1) == word2.charAt(j-1))
dp[i][j] = dp[i-1][j-1] + 1;
else
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
return (m+n)-dp[m][n] * 2;
}
}``````

原文作者：酷记麻辣油
原文地址: https://blog.csdn.net/qq_40320556/article/details/89951179
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。