给定两个单词 word1 和 word2 ,返回使得 word1 和 word2 相同所需的最小步数。
每步 可以删除任意一个字符串中的一个字符。
示例 1:
输入: word1 = "sea", word2 = "eat"
输出: 2
解释: 第一步将 "sea" 变为 "ea" ,第二步将 "eat "变为 "ea"
示例 2:
输入:word1 = "leetcode", word2 = "etco"
输出:4
提示:
1 <= word1.length, word2.length <= 500
word1 和 word2 只包含小写英文字母
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/delete-operation-for-two-strings
思路:
本题可以先将两个字符串的最长公共子序列求出来,然后 两个字符串的长度,分别前去最长公共子序列的长度求和以后,得到的结果就是需要删除的字符数目。
java:
class Solution {
public int minDistance(String word1, String word2) {
int maxLen = longestCommonSubsequence(word1,word2);
return (word1.length() - maxLen) + (word2.length() - maxLen);
}
public int longestCommonSubsequence(String text1, String text2) {
int[][] dp = new int[text1.length()][text2.length()];
if (text1.length() == 0 || text2.length() == 0) {
return 0;
}
// 1. 初始化 base
for (int i = 0; i < text1.length(); i++) {
if (text2.charAt(0) == text1.charAt(i)) {
dp[i][0] = 1;
}
if (i > 0) {
dp[i][0] = Math.max(dp[i][0],dp[i-1][0]);
}
}
for (int j = 0; j < text2.length(); j++) {
if (text1.charAt(0) == text2.charAt(j)) {
dp[0][j] = 1;
}
if(j>0) {
dp[0][j] = Math.max(dp[0][j],dp[0][j-1]);
}
}
// 2. 状态转移方程
for (int i = 1; i < text1.length(); i++) {
for (int j = 1; j < text2.length(); j++) {
if (text1.charAt(i) == text2.charAt(j)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j - 1], dp[i][j - 1]);
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]);
}
}
}
return dp[text1.length() - 1][text2.length() - 1];
}
}



