给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。
示例 1:
输入: "sea", "eat" 输出: 2 解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"
说明:
- 给定单词的长度不超过500。
- 给定单词中的字符只含有小写字母。
先计算两个字符串的公共子序列,然后将两个字符串都变为公共子序列,就可以计算出最少需要删去的字符数
/*
* @lc app=leetcode.cn id=583 lang=java
*
* [583] 两个字符串的删除操作
* dp[i][j] 表示word1的前i个字符和word2的前j的字符的
* 最长公共子序列的长度
*/
class Solution {
public int minDistance(String word1, String word2) {
int[][] dp = new int[word1.length()+1][word2.length()+1];
for(int i=1;i<=word1.length();i++){
for(int j=1;j<=word2.length();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 word1.length()+word2.length()-2*dp[word1.length()][word2.length()];
}
}