Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 18, 2023
1 parent 28c944d commit a4d9ec0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
26 changes: 12 additions & 14 deletions src/problem_0072_edit_distance/dynamic_programming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,33 @@ pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::mem;

impl Solution {
pub fn min_distance(word1: String, word2: String) -> i32 {
let (word1, word2) = if word2.len() < word1.len() {
(word2, word1)
(word2.as_str(), word1.as_str())
} else {
(word1, word2)
(word1.as_str(), word2.as_str())
};

let mut cache = (0..=word1.len() as _).rev().collect::<Box<_>>();

for (prev_base, c2) in word2.as_bytes().iter().rev().enumerate() {
let mut prev = prev_base as _;
let mut cache = (1..=word1.len() as u16).collect::<Box<_>>();

cache[word1.len()] = prev + 1;
for (mut top_left, c1) in (0..).zip(word2.bytes()) {
let mut left = top_left + 1;

for (i, c1) in word1.as_bytes().iter().enumerate().rev() {
for (target, c2) in cache.iter_mut().zip(word1.bytes()) {
let distance = if c1 == c2 {
prev
top_left
} else {
cache[i].min(cache[i + 1]).min(prev) + 1
top_left.min(*target).min(left) + 1
};

prev = mem::replace(&mut cache[i], distance);
top_left = *target;
left = distance;
*target = distance;
}
}

cache[0]
cache.last().map_or(word2.len() as _, |&last| i32::from(last))
}
}

Expand Down
7 changes: 6 additions & 1 deletion src/problem_0072_edit_distance/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [(("horse", "ros"), 3), (("intention", "execution"), 5), (("", "a"), 1)];
let test_cases = [
(("horse", "ros"), 3),
(("intention", "execution"), 5),
(("", "a"), 1),
(("plasma", "altruism"), 6),
];

for ((word1, word2), expected) in test_cases {
assert_eq!(S::min_distance(word1.to_string(), word2.to_string()), expected);
Expand Down

0 comments on commit a4d9ec0

Please sign in to comment.