代码随想录 Day56 - 动态规划(十六)
作者:jjn0703
- 2023-08-26 江苏
本文字数:1244 字
阅读完需:约 4 分钟
作业题
583.两个字符串的删除操作
链接:https://leetcode.cn/problems/delete-operation-for-two-strings/description/
package jjn.carl.dp;
import java.util.Scanner;
/**
* @author Jjn
* @since 2023/8/26 20:47
*/
public class LeetCode583 {
public int minDistance(String word1, String word2) {
int[][] dp = new int[word1.length() + 1][word2.length() + 1];
for (int i = 0; i < word1.length() + 1; i++) dp[i][0] = i;
for (int j = 0; j < word2.length() + 1; j++) dp[0][j] = j;
for (int i = 1; i < word1.length() + 1; i++) {
for (int j = 1; j < word2.length() + 1; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i - 1][j - 1] + 2,
Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1));
}
}
}
return dp[word1.length()][word2.length()];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word1 = scanner.next();
String word2 = scanner.next();
int minDistance = new LeetCode583().minDistance(word1, word2);
System.out.println(minDistance);
}
}
复制代码
72.编辑距离
链接:https://leetcode.cn/problems/edit-distance/description/
package jjn.carl.dp;
import java.util.Scanner;
/**
* @author Jjn
* @since 2023/8/26 21:40
*/
public class LeetCode72 {
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= n; i++) {
dp[0][i] = i;
}
for (int i = 0; i <= m; i++) {
dp[i][0] = i;
}
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];
} else {
dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
}
}
}
return dp[m][n];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word1 = scanner.next();
String word2 = scanner.next();
int minDistance = new LeetCode72().minDistance(word1, word2);
System.out.println(minDistance);
}
}
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 2
版权声明: 本文为 InfoQ 作者【jjn0703】的原创文章。
原文链接:【http://xie.infoq.cn/article/e22a49406f80226123f325dbd】。
本文遵守【CC-BY 4.0】协议,转载请保留原文出处及本版权声明。
jjn0703
关注
Java工程师/终身学习者 2018-03-26 加入
USTC硕士/健身健美爱好者/Java工程师.
评论