Skip to content

Commit 591a014

Browse files
committed
feat: add cache
1 parent 6978cd3 commit 591a014

File tree

1 file changed

+27
-13
lines changed

1 file changed

+27
-13
lines changed

edit_distance/src/lib.rs

+27-13
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,37 @@ struct Solution {}
1010

1111
// ----------------------------------------------------------------------------
1212

13+
use std::collections::HashMap;
14+
1315
impl Solution {
14-
pub fn min_distance(word1: String, word2: String) -> i32 {
15-
if word1.len() == 0 {
16-
return word2.len() as i32;
17-
}
18-
if word2.len() == 0 {
19-
return word1.len() as i32;
16+
pub fn reduce_min_distance(
17+
word1: String,
18+
word2: String,
19+
cache: &mut HashMap<(String, String), usize>,
20+
) -> usize {
21+
let (length1, length2) = (word1.len(), word2.len());
22+
if length1 == 0 || length2 == 0 {
23+
let min = length1.max(length2);
24+
cache.insert((word1.clone(), word2.clone()), min);
25+
return min;
2026
}
21-
let w1 = word1[1..].to_string();
22-
let w2 = word2[1..].to_string();
27+
let word1_slice = word1[1..].to_string();
28+
let word2_slice = word2[1..].to_string();
2329
if word1.chars().next().unwrap() == word2.chars().next().unwrap() {
24-
return Solution::min_distance(w1.clone(), w2.clone());
30+
return Solution::reduce_min_distance(word1_slice.clone(), word2_slice.clone(), cache);
2531
}
26-
let insert = 1 + Solution::min_distance(word1.clone(), w2.clone()); // insert the first char of word2 in front of word1
27-
let delete = 1 + Solution::min_distance(w1.clone(), word2.clone()); // delete the first char of word1
28-
let edit = 1 + Solution::min_distance(w1.clone(), w2.clone()); // change from the first char of word1 to the one of word2
29-
*[insert, delete, edit].iter().min().unwrap()
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
36+
let min = *[insert, delete, edit].iter().min().unwrap();
37+
cache.insert((word1.clone(), word2.clone()), min);
38+
min
39+
}
40+
41+
pub fn min_distance(word1: String, word2: String) -> i32 {
42+
let mut cache = HashMap::new();
43+
Self::reduce_min_distance(word1, word2, &mut cache) as i32
3044
}
3145
}
3246

0 commit comments

Comments
 (0)