From 5818811a53f299b937cb29f5f7be142321aaf83d Mon Sep 17 00:00:00 2001 From: li-chx Date: Thu, 13 Aug 2026 11:21:50 +0800 Subject: [PATCH] =?UTF-8?q?1143.=20=E6=9C=80=E9=95=BF=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/src/main.rs b/src/main.rs index 5eee5a3..1a52487 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,29 +1,24 @@ mod arr; struct Solution {} impl Solution { - pub fn min_distance(word1: String, word2: String) -> i32 { - let mut dp = vec![vec![0; word2.len() + 1]; word1.len() + 1]; - let word1 = word1.chars().collect::>(); - let word2 = word2.chars().collect::>(); - for i in 1..=word1.len() { - dp[i][0] = dp[i - 1][0] + 1; - } - for i in 1..=word2.len() { - dp[0][i] = dp[0][i - 1] + 1; - } - for i in 0..word1.len() { - for j in 0..word2.len() { - dp[i + 1][j + 1] = (dp[i][j] + if word1[i] != word2[j] { 1 } else { 0 }) - .min(dp[i][j + 1] + 1) - .min(dp[i + 1][j] + 1); + pub fn longest_common_subsequence(text1: String, text2: String) -> i32 { + let mut dp = vec![vec![0; text2.len() + 1]; text1.len() + 1]; + let text1 = text1.chars().collect::>(); + let text2 = text2.chars().collect::>(); + for i in 0..text1.len() { + for j in 0..text2.len() { + dp[i + 1][j + 1] = dp[i + 1][j].max(dp[i][j + 1]); + if text1[i] == text2[j] { + dp[i + 1][j + 1] = dp[i + 1][j + 1].max(dp[i][j] + 1); + } } } - dp[word1.len()][word2.len()] + dp[text1.len()][text2.len()] } } fn main() { println!( "{:?}", - Solution::min_distance("intention".to_string(), "execution".to_string()) + Solution::longest_common_subsequence("abcde".to_string(), "ace".to_string()) ); }