From 5c1d526ff9e476bd8f957d9f6fae95a73ca18761 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 12 Aug 2024 11:35:10 +0800 Subject: [PATCH] 20240812 Finished --- src/problem/mod.rs | 3 +- src/problem/p72_edit_distance.rs | 57 ++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 src/problem/p72_edit_distance.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 7c97390..27b880f 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -201,4 +201,5 @@ mod p300_longest_increasing_subsequence; mod p120_triangle; mod p64_minimum_path_sum; mod p63_unique_paths_ii; -mod p97_interleaving_string; \ No newline at end of file +mod p97_interleaving_string; +mod p72_edit_distance; \ No newline at end of file diff --git a/src/problem/p72_edit_distance.rs b/src/problem/p72_edit_distance.rs new file mode 100644 index 0000000..49ccf51 --- /dev/null +++ b/src/problem/p72_edit_distance.rs @@ -0,0 +1,57 @@ +/** + * [72] Edit Distance + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn min_distance(word1: String, word2: String) -> i32 { + let (word1, word2): (Vec, Vec) = (word1.chars().collect(), word2.chars().collect()); + let (n, m) = (word1.len(), word2.len()); + + // 存在一个字符串有空串 + if m * n == 0 { + return (m + n) as i32; + } + + let mut dp = vec![vec![0;m + 1]; n + 1]; + + // 初始化dp数组 + for i in 0..=n { + dp[i][0] = i; + } + + for i in 0..=m { + dp[0][i] = i; + } + + for i in 1..=n { + for j in 1..=m { + let left = dp[i - 1][j] + 1; + let down = dp[i][j - 1] + 1; + let mut left_down = dp[i - 1][ j -1]; + if word1[i - 1] != word2[j - 1] { + left_down += 1; + } + + dp[i][j] = left.min(down).min(left_down); + } + } + + dp[n][m] as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_72() { + assert_eq!(3, Solution::min_distance("horse".to_owned(), "ros".to_owned())); + } +}