From 0fed2a54a319160b17fe5cea69dd4fedd1e7e053 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Fri, 30 Dec 2022 15:24:06 +0800 Subject: [PATCH] =?UTF-8?q?update=201143.=E6=9C=80=E9=95=BF=E5=85=AC?= =?UTF-8?q?=E5=85=B1=E5=AD=90=E5=BA=8F=E5=88=97=EF=BC=9A=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=96=87=E6=9C=AC=E9=94=99=E5=AD=97=EF=BC=8C=E8=B0=83=E6=95=B4?= =?UTF-8?q?=20rust=20=E4=BB=A3=E7=A0=81=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1143.最长公共子序列.md | 43 +++++++++++++------------- 1 file changed, 21 insertions(+), 22 deletions(-) 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] +} +```