@@ -9,19 +9,25 @@ pub struct Solution {}
9
9
10
10
impl Solution {
11
11
pub fn min_distance ( word1 : String , word2 : String ) -> i32 {
12
- let common_length = Self :: lcs ( & word1, & word2, word1. len ( ) , word2. len ( ) ) ;
12
+ let mut dp = vec ! [ vec![ None ; word2. len( ) + 1 ] ; word1. len( ) + 1 ] ;
13
+ let common_length = Self :: lcs ( & word1, & word2, word1. len ( ) , word2. len ( ) , & mut dp) ;
13
14
( word1. len ( ) + word2. len ( ) - 2 * common_length) as i32
14
15
}
15
16
16
- pub fn lcs ( s1 : & str , s2 : & str , m : usize , n : usize ) -> usize {
17
+ fn lcs ( s1 : & str , s2 : & str , m : usize , n : usize , dp : & mut Vec < Vec < Option < usize > > > ) -> usize {
17
18
// comparing first m characters in s1 and first n characters in s2
18
- if m == 0 || n == 0 {
19
+ if let Some ( length) = dp[ m] [ n] {
20
+ return length;
21
+ }
22
+ let length = if m == 0 || n == 0 {
19
23
0
20
24
} else if s1. chars ( ) . nth ( m - 1 ) == s2. chars ( ) . nth ( n - 1 ) {
21
- 1 + Self :: lcs ( s1, s2, m - 1 , n - 1 )
25
+ 1 + Self :: lcs ( s1, s2, m - 1 , n - 1 , dp )
22
26
} else {
23
- Self :: lcs ( s1, s2, m - 1 , n) . max ( Self :: lcs ( s1, s2, m, n - 1 ) )
24
- }
27
+ Self :: lcs ( s1, s2, m - 1 , n, dp) . max ( Self :: lcs ( s1, s2, m, n - 1 , dp) )
28
+ } ;
29
+ dp[ m] [ n] = Some ( length) ;
30
+ length
25
31
}
26
32
}
27
33
@@ -34,8 +40,9 @@ mod test {
34
40
let word1 = "sea" ;
35
41
let word2 = "eat" ;
36
42
let expected = 2 ;
43
+ let mut dp = vec ! [ vec![ None ; word2. len( ) + 1 ] ; word1. len( ) + 1 ] ;
37
44
assert_eq ! (
38
- Solution :: lcs( word1, word2, word1. len( ) , word2. len( ) ) ,
45
+ Solution :: lcs( word1, word2, word1. len( ) , word2. len( ) , & mut dp ) ,
39
46
expected
40
47
) ;
41
48
}
0 commit comments