From 60bb5dc4fc2288182542422fce73691bc120608f Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 24 Jul 2023 23:27:11 +0800 Subject: [PATCH] =?UTF-8?q?Update=200072.=E7=BC=96=E8=BE=91=E8=B7=9D?= =?UTF-8?q?=E7=A6=BB.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0072.编辑距离.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0072.编辑距离.md b/problems/0072.编辑距离.md index 19e7aade..15f35f6c 100644 --- a/problems/0072.编辑距离.md +++ b/problems/0072.编辑距离.md @@ -429,6 +429,36 @@ impl Solution { } ``` +> 一维 dp + +```rust +impl Solution { + pub fn min_distance(word1: String, word2: String) -> i32 { + let mut dp = vec![0; word1.len() + 1]; + for (i, v) in dp.iter_mut().enumerate().skip(1) { + *v = i; + } + + for char2 in word2.chars() { + // 相当于 dp[i][0] 的初始化 + let mut pre = dp[0]; + dp[0] += 1; // j = 0, 将前 i 个字符变成空串的个数 + for (j, char1) in word1.chars().enumerate() { + let temp = dp[j + 1]; + if char1 == char2 { + dp[j + 1] = pre; + } else { + dp[j + 1] = dp[j + 1].min(dp[j]).min(pre) + 1; + } + pre = temp; + } + } + + dp[word1.len()] as i32 + } +} +``` +