diff --git a/problems/1143.最长公共子序列.md b/problems/1143.最长公共子序列.md index b655b5cd..f2e6e7e2 100644 --- a/problems/1143.最长公共子序列.md +++ b/problems/1143.最长公共子序列.md @@ -49,7 +49,7 @@ dp[i][j]:长度为[0, i - 1]的字符串text1与长度为[0, j - 1]的字符 有同学会问:为什么要定义长度为[0, i - 1]的字符串text1,定义为长度为[0, i]的字符串text1不香么? -这样定义是为了后面代码实现方便,如果非要定义为为长度为[0, i]的字符串text1也可以,我在 [动态规划:718. 最长重复子数组](https://programmercarl.com/0718.最长重复子数组.html) 中的「拓展」里 详细讲解了区别所在,其实就是简化了dp数组第一行和第一列的初始化逻辑。 +这样定义是为了后面代码实现方便,如果非要定义为长度为[0, i]的字符串text1也可以,我在 [动态规划:718. 最长重复子数组](https://programmercarl.com/0718.最长重复子数组.html) 中的「拓展」里 详细讲解了区别所在,其实就是简化了dp数组第一行和第一列的初始化逻辑。 2. 确定递推公式 @@ -240,27 +240,6 @@ func max(a,b int)int { ``` -Rust: -```rust -pub fn longest_common_subsequence(text1: String, text2: String) -> i32 { - let (n, m) = (text1.len(), text2.len()); - let (s1, s2) = (text1.as_bytes(), text2.as_bytes()); - let mut dp = vec![0; m + 1]; - let mut last = vec![0; m + 1]; - for i in 1..=n { - dp.swap_with_slice(&mut last); - for j in 1..=m { - dp[j] = if s1[i - 1] == s2[j - 1] { - last[j - 1] + 1 - } else { - last[j].max(dp[j - 1]) - }; - } - } - dp[m] -} -``` - Javascript: ```javascript const longestCommonSubsequence = (text1, text2) => { @@ -304,6 +283,26 @@ function longestCommonSubsequence(text1: string, text2: string): number { }; ``` +Rust: +```rust +pub fn longest_common_subsequence(text1: String, text2: String) -> i32 { + let (n, m) = (text1.len(), text2.len()); + let (s1, s2) = (text1.as_bytes(), text2.as_bytes()); + let mut dp = vec![0; m + 1]; + let mut last = vec![0; m + 1]; + for i in 1..=n { + dp.swap_with_slice(&mut last); + for j in 1..=m { + dp[j] = if s1[i - 1] == s2[j - 1] { + last[j - 1] + 1 + } else { + last[j].max(dp[j - 1]) + }; + } + } + dp[m] +} +```