Skip to content

Commit 0fed2a5

Browse files
authored
update 1143.最长公共子序列:优化文本错字,调整 rust 代码位置
1 parent 2afe270 commit 0fed2a5

File tree

1 file changed

+21
-22
lines changed

1 file changed

+21
-22
lines changed

problems/1143.最长公共子序列.md

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ dp[i][j]:长度为[0, i - 1]的字符串text1与长度为[0, j - 1]的字符
4949

5050
有同学会问:为什么要定义长度为[0, i - 1]的字符串text1,定义为长度为[0, i]的字符串text1不香么?
5151

52-
这样定义是为了后面代码实现方便,如果非要定义为为长度为[0, i]的字符串text1也可以,我在 [动态规划:718. 最长重复子数组](https://programmercarl.com/0718.最长重复子数组.html) 中的「拓展」里 详细讲解了区别所在,其实就是简化了dp数组第一行和第一列的初始化逻辑。
52+
这样定义是为了后面代码实现方便,如果非要定义为长度为[0, i]的字符串text1也可以,我在 [动态规划:718. 最长重复子数组](https://programmercarl.com/0718.最长重复子数组.html) 中的「拓展」里 详细讲解了区别所在,其实就是简化了dp数组第一行和第一列的初始化逻辑。
5353

5454
2. 确定递推公式
5555

@@ -240,27 +240,6 @@ func max(a,b int)int {
240240

241241
```
242242

243-
Rust:
244-
```rust
245-
pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
246-
let (n, m) = (text1.len(), text2.len());
247-
let (s1, s2) = (text1.as_bytes(), text2.as_bytes());
248-
let mut dp = vec![0; m + 1];
249-
let mut last = vec![0; m + 1];
250-
for i in 1..=n {
251-
dp.swap_with_slice(&mut last);
252-
for j in 1..=m {
253-
dp[j] = if s1[i - 1] == s2[j - 1] {
254-
last[j - 1] + 1
255-
} else {
256-
last[j].max(dp[j - 1])
257-
};
258-
}
259-
}
260-
dp[m]
261-
}
262-
```
263-
264243
Javascript:
265244
```javascript
266245
const longestCommonSubsequence = (text1, text2) => {
@@ -304,6 +283,26 @@ function longestCommonSubsequence(text1: string, text2: string): number {
304283
};
305284
```
306285

286+
Rust:
287+
```rust
288+
pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
289+
let (n, m) = (text1.len(), text2.len());
290+
let (s1, s2) = (text1.as_bytes(), text2.as_bytes());
291+
let mut dp = vec![0; m + 1];
292+
let mut last = vec![0; m + 1];
293+
for i in 1..=n {
294+
dp.swap_with_slice(&mut last);
295+
for j in 1..=m {
296+
dp[j] = if s1[i - 1] == s2[j - 1] {
297+
last[j - 1] + 1
298+
} else {
299+
last[j].max(dp[j - 1])
300+
};
301+
}
302+
}
303+
dp[m]
304+
}
305+
```
307306

308307

309308

0 commit comments

Comments
 (0)