mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0072.编辑距离.md
This commit is contained in:
@ -429,6 +429,36 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> 一维 dp
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn min_distance(word1: String, word2: String) -> i32 {
|
||||||
|
let mut dp = vec![0; word1.len() + 1];
|
||||||
|
for (i, v) in dp.iter_mut().enumerate().skip(1) {
|
||||||
|
*v = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
for char2 in word2.chars() {
|
||||||
|
// 相当于 dp[i][0] 的初始化
|
||||||
|
let mut pre = dp[0];
|
||||||
|
dp[0] += 1; // j = 0, 将前 i 个字符变成空串的个数
|
||||||
|
for (j, char1) in word1.chars().enumerate() {
|
||||||
|
let temp = dp[j + 1];
|
||||||
|
if char1 == char2 {
|
||||||
|
dp[j + 1] = pre;
|
||||||
|
} else {
|
||||||
|
dp[j + 1] = dp[j + 1].min(dp[j]).min(pre) + 1;
|
||||||
|
}
|
||||||
|
pre = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dp[word1.len()] as i32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
|
Reference in New Issue
Block a user