代码随想录训练营 Day56
今日任务
583.两个字符串的删除操作
72.编辑距离
编辑距离总结
语言:Java
583. 两个字符串的删除操作
链接:https://leetcode.cn/problems/delete-operation-for-two-strings/
class Solution {
public int minDistance(String word1, String word2) {
//可以转化成最长子串问题
//dp[i][j]表示以word2[i-1]结尾的子字符串和以word1[j-1]结尾的子字符串的最大公共子串长度
int[][] dp = new int[word2.length() + 1][word1.length() + 1];
for(int i = 1; i <= word2.length(); i++){
for(int j = 1; j <= word1.length(); j++){
if(word1.charAt(j - 1) == word2.charAt(i - 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() - dp[word2.length()][word1.length()] * 2;
}
}
/*
- s e a
- 0 0 0 0
e 0 0 1 1
a 0 0 1 2
t 0 0 1 2
*/
72. 编辑距离
链接:https://leetcode.cn/problems/edit-distance/
class Solution {
public int minDistance(String word1, String word2) {
int[][] dp = new int[word2.length() + 1][word1.length() + 1];
//以word1[j-1]结尾的word1子字符串和以word2[i-1]结尾的word2子字符串的最小编辑距离为dp[i][j]
//word1删除元素=word2插入元素: dp[i][j-1]+1
//word2删除元素=word1插入元素: dp[i-1][j]+1
//word1或word2替换元素: dp[i-1][j-1]+1
for(int i = 0; i <= word2.length(); i++){
dp[i][0] = i;
}
for(int j = 0; j <= word1.length(); j++){
dp[0][j] = j;
}
for(int i = 1; i <= word2.length(); i++){
for(int j = 1; j <= word1.length(); j++){
if(word1.charAt(j - 1) == word2.charAt(i - 1)){
dp[i][j] = dp[i - 1][j - 1];
}
else{
dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
}
}
}
return dp[word2.length()][word1.length()];
}
}
/*
- h o r s e
- 0 1 2 3 4 5
r 1 1 2 2 3 4
o 2 2 1 2 3 3
s 3 3 2 2 2 3
*/