mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
update 1143.最长公共子序列:优化文本错字,调整 rust 代码位置
This commit is contained in:
@ -49,7 +49,7 @@ dp[i][j]:长度为[0, i - 1]的字符串text1与长度为[0, j - 1]的字符
|
|||||||
|
|
||||||
有同学会问:为什么要定义长度为[0, i - 1]的字符串text1,定义为长度为[0, i]的字符串text1不香么?
|
有同学会问:为什么要定义长度为[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. 确定递推公式
|
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:
|
||||||
```javascript
|
```javascript
|
||||||
const longestCommonSubsequence = (text1, text2) => {
|
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]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user