0583. Delete Operation for Two Strings (M)
Delete Operation for Two Strings (M)
题目
Given two strings word1
and word2
, return the minimum number of steps required to make word1
and word2
the same.
In one step, you can delete exactly one character in either string.
Example 1:
Input: word1 = "sea", word2 = "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
Example 2:
Input: word1 = "leetcode", word2 = "etco"
Output: 4
Constraints:
1 <= word1.length, word2.length <= 500
word1
andword2
consist of only lowercase English letters.
题意
给定两个字符串,每次能从任一个字符串中删去一个字符,问最少经过多少次操作能使两个字符串相等。
思路
经典动态规划问题“两个字符串的编辑距离”的变种。dp[x][y]表示使s1中的前x个字符组成的子串s1(x)与s2中的前y个字符组成的子串s2(y)相等所需要的最小步数,那么有三种情况:(1) dp[x][y] = dp[x][y-1] + 1,删去s2的最后一个字符,只要求使s1(x)和s2(y-1)相等所需的步数;(2) dp[x][y] = dp[x-1][y] + 1,删去s1的最后一个字符,只要求使s1(x-1)和s2(y)相等所需的步数;(3) dp[x][y] = dp[x-1][y-1] + 0/2,如果最后一个字符相同,则只需求使s1(x-1)和s2(y-1)相等的步数,如果不相同,则先删去各自最后一个字符,再求步数。
代码实现
Java
class Solution {
public int minDistance(String word1, String word2) {
int[][] dp = new int[word1.length() + 1][word2.length() + 1];
for (int i = 0; i <= word1.length(); i++) {
for (int j = 0; j <= word2.length(); j++) {
dp[i][j] = Integer.MAX_VALUE;
if (i == 0 || j == 0) {
dp[i][j] = i == 0 ? j : i;
} else {
dp[i][j] = Math.min(dp[i][j], dp[i-1][j] + 1);
dp[i][j] = Math.min(dp[i][j], dp[i][j-1] + 1);
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + (word1.charAt(i - 1) == word2.charAt(j - 1) ? 0 : 2));
}
}
}
return dp[word1.length()][word2.length()];
}
}