Skip to content

Commit 7e5ef62

Browse files
committed
feat: use cache
1 parent 591a014 commit 7e5ef62

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

edit_distance/src/lib.rs

+12-10
Original file line numberDiff line numberDiff line change
@@ -14,33 +14,35 @@ use std::collections::HashMap;
1414

1515
impl Solution {
1616
pub fn reduce_min_distance(
17-
word1: String,
18-
word2: String,
17+
word1: &str,
18+
word2: &str,
1919
cache: &mut HashMap<(String, String), usize>,
2020
) -> usize {
21+
if let Some(&min) = cache.get(&(word1.to_string(), word2.to_string())) {
22+
return min;
23+
};
2124
let (length1, length2) = (word1.len(), word2.len());
2225
if length1 == 0 || length2 == 0 {
2326
let min = length1.max(length2);
24-
cache.insert((word1.clone(), word2.clone()), min);
27+
cache.insert((word1.to_string(), word2.to_string()), min);
2528
return min;
2629
}
2730
let word1_slice = word1[1..].to_string();
2831
let word2_slice = word2[1..].to_string();
2932
if word1.chars().next().unwrap() == word2.chars().next().unwrap() {
30-
return Solution::reduce_min_distance(word1_slice.clone(), word2_slice.clone(), cache);
33+
return Solution::reduce_min_distance(&word1_slice, &word2_slice, cache);
3134
}
32-
let insert = 1 + Solution::reduce_min_distance(word1.clone(), word2_slice.clone(), cache); // insert the first char of word2 in front of word1
33-
let delete = 1 + Solution::reduce_min_distance(word1_slice.clone(), word2.clone(), cache); // delete the first char of word1
34-
let edit =
35-
1 + Solution::reduce_min_distance(word1_slice.clone(), word2_slice.clone(), cache); // change from the first char of word1 to the one of word2
35+
let insert = 1 + Solution::reduce_min_distance(word1, &word2_slice, cache); // insert the first char of word2 in front of word1
36+
let delete = 1 + Solution::reduce_min_distance(&word1_slice, word2, cache); // delete the first char of word1
37+
let edit = 1 + Solution::reduce_min_distance(&word1_slice, &word2_slice, cache); // change from the first char of word1 to the one of word2
3638
let min = *[insert, delete, edit].iter().min().unwrap();
37-
cache.insert((word1.clone(), word2.clone()), min);
39+
cache.insert((word1.to_string(), word2.to_string()), min);
3840
min
3941
}
4042

4143
pub fn min_distance(word1: String, word2: String) -> i32 {
4244
let mut cache = HashMap::new();
43-
Self::reduce_min_distance(word1, word2, &mut cache) as i32
45+
Self::reduce_min_distance(&word1, &word2, &mut cache) as i32
4446
}
4547
}
4648

0 commit comments

Comments
 (0)