From 58b2b1e1134625104469000548443f1ae57afb0d Mon Sep 17 00:00:00 2001 From: Cool <747682928@qq.com> Date: Mon, 30 Sep 2024 01:55:17 +0800 Subject: [PATCH] =?UTF-8?q?2024/9/29=20=E5=A4=9A=E7=BB=B4dp=20=E6=9C=80?= =?UTF-8?q?=E5=90=8E=E4=B8=80=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/cool/hot100/multi_dp/Num72.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/com/cool/hot100/multi_dp/Num72.java diff --git a/src/main/java/com/cool/hot100/multi_dp/Num72.java b/src/main/java/com/cool/hot100/multi_dp/Num72.java new file mode 100644 index 0000000..9a04b74 --- /dev/null +++ b/src/main/java/com/cool/hot100/multi_dp/Num72.java @@ -0,0 +1,41 @@ +package com.cool.hot100.multi_dp; + +/** + * Created with IntelliJ IDEA. + * + * @Author: Cool + * @Date: 2024/09/30/1:53 + * @Description: 72. 编辑距离 + * Hard 2 看似mid实则hard + * Level 6 + * DayNumber 3 + * @Link https://leetcode.cn/problems/edit-distance/description/?envType=study-plan-v2&envId=top-100-liked + */ +public class Num72 { + public int minDistance(String word1, String word2) { + int nLen = word1.length(); + int mLen = word2.length(); + if (nLen * mLen == 0) { + return mLen + nLen; + } + int[][] dp = new int[nLen + 1][mLen + 1]; + for (int i = 0; i < nLen + 1; i++) { + dp[i][0] = i; + } + for (int i = 0; i < mLen + 1; i++) { + dp[0][i] = i; + } + for (int i = 1; i < nLen + 1; i++) { + for (int j = 1; j < mLen + 1; j++) { + int leftToRight = dp[i - 1][j]; + int rightToLeft = dp[i][j - 1]; + int leftAndRight = dp[i - 1][j - 1]; + if (word1.charAt(i - 1) == word2.charAt(j - 1)) { + leftAndRight--; + } + dp[i][j] = Math.min(leftAndRight, Math.min(leftToRight, rightToLeft)) + 1; + } + } + return dp[nLen][mLen]; + } +}