mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 1143.最长公共子序列.md about rust
This commit is contained in:
@ -327,23 +327,51 @@ function longestCommonSubsequence(text1: string, text2: string): number {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Rust:
|
Rust:
|
||||||
|
|
||||||
|
二维 dp:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
|
impl Solution {
|
||||||
let (n, m) = (text1.len(), text2.len());
|
pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
|
||||||
let (s1, s2) = (text1.as_bytes(), text2.as_bytes());
|
let mut dp = vec![vec![0; text2.len() + 1]; text1.len() + 1];
|
||||||
let mut dp = vec![0; m + 1];
|
for (i, c1) in text1.chars().enumerate() {
|
||||||
let mut last = vec![0; m + 1];
|
for (j, c2) in text2.chars().enumerate() {
|
||||||
for i in 1..=n {
|
if c1 == c2 {
|
||||||
dp.swap_with_slice(&mut last);
|
dp[i + 1][j + 1] = dp[i][j] + 1;
|
||||||
for j in 1..=m {
|
|
||||||
dp[j] = if s1[i - 1] == s2[j - 1] {
|
|
||||||
last[j - 1] + 1
|
|
||||||
} else {
|
} else {
|
||||||
last[j].max(dp[j - 1])
|
dp[i + 1][j + 1] = dp[i][j + 1].max(dp[i + 1][j]);
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
dp[m]
|
}
|
||||||
|
dp[text1.len()][text2.len()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
二维:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
|
||||||
|
let mut dp = vec![0; text2.len() + 1];
|
||||||
|
for c1 in text1.chars() {
|
||||||
|
// 初始化 prev
|
||||||
|
let mut prev = 0;
|
||||||
|
|
||||||
|
for (j, c2) in text2.chars().enumerate() {
|
||||||
|
let temp = dp[j + 1];
|
||||||
|
if c1 == c2 {
|
||||||
|
// 使用上一次的状态,防止重复计算
|
||||||
|
dp[j + 1] = prev + 1;
|
||||||
|
} else {
|
||||||
|
dp[j + 1] = dp[j + 1].max(dp[j]);
|
||||||
|
}
|
||||||
|
// 使用上一次的状态更新 prev
|
||||||
|
prev = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dp[text2.len()]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user