1143. 最长公共子序列

This commit is contained in:
2026-08-13 11:21:50 +08:00
parent 551db6decf
commit 5818811a53
+12 -17
View File
@@ -1,29 +1,24 @@
mod arr; mod arr;
struct Solution {} struct Solution {}
impl Solution { impl Solution {
pub fn min_distance(word1: String, word2: String) -> i32 { pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
let mut dp = vec![vec![0; word2.len() + 1]; word1.len() + 1]; let mut dp = vec![vec![0; text2.len() + 1]; text1.len() + 1];
let word1 = word1.chars().collect::<Vec<char>>(); let text1 = text1.chars().collect::<Vec<char>>();
let word2 = word2.chars().collect::<Vec<char>>(); let text2 = text2.chars().collect::<Vec<char>>();
for i in 1..=word1.len() { for i in 0..text1.len() {
dp[i][0] = dp[i - 1][0] + 1; for j in 0..text2.len() {
} dp[i + 1][j + 1] = dp[i + 1][j].max(dp[i][j + 1]);
for i in 1..=word2.len() { if text1[i] == text2[j] {
dp[0][i] = dp[0][i - 1] + 1; dp[i + 1][j + 1] = dp[i + 1][j + 1].max(dp[i][j] + 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);
} }
} }
dp[word1.len()][word2.len()] dp[text1.len()][text2.len()]
} }
} }
fn main() { fn main() {
println!( println!(
"{:?}", "{:?}",
Solution::min_distance("intention".to_string(), "execution".to_string()) Solution::longest_common_subsequence("abcde".to_string(), "ace".to_string())
); );
} }