@@ -14,33 +14,35 @@ use std::collections::HashMap;
14
14
15
15
impl Solution {
16
16
pub fn reduce_min_distance (
17
- word1 : String ,
18
- word2 : String ,
17
+ word1 : & str ,
18
+ word2 : & str ,
19
19
cache : & mut HashMap < ( String , String ) , usize > ,
20
20
) -> usize {
21
+ if let Some ( & min) = cache. get ( & ( word1. to_string ( ) , word2. to_string ( ) ) ) {
22
+ return min;
23
+ } ;
21
24
let ( length1, length2) = ( word1. len ( ) , word2. len ( ) ) ;
22
25
if length1 == 0 || length2 == 0 {
23
26
let min = length1. max ( length2) ;
24
- cache. insert ( ( word1. clone ( ) , word2. clone ( ) ) , min) ;
27
+ cache. insert ( ( word1. to_string ( ) , word2. to_string ( ) ) , min) ;
25
28
return min;
26
29
}
27
30
let word1_slice = word1[ 1 ..] . to_string ( ) ;
28
31
let word2_slice = word2[ 1 ..] . to_string ( ) ;
29
32
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) ;
31
34
}
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
36
38
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) ;
38
40
min
39
41
}
40
42
41
43
pub fn min_distance ( word1 : String , word2 : String ) -> i32 {
42
44
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
44
46
}
45
47
}
46
48
0 commit comments