File tree Expand file tree Collapse file tree 1 file changed +15
-1
lines changed Expand file tree Collapse file tree 1 file changed +15
-1
lines changed Original file line number Diff line number Diff line change @@ -12,7 +12,21 @@ struct Solution {}
12
12
13
13
impl Solution {
14
14
pub fn min_distance ( word1 : String , word2 : String ) -> i32 {
15
- 3
15
+ if word1. len ( ) == 0 {
16
+ return word2. len ( ) as i32 ;
17
+ }
18
+ if word2. len ( ) == 0 {
19
+ return word1. len ( ) as i32 ;
20
+ }
21
+ let w1 = word1[ 1 ..] . to_string ( ) ;
22
+ let w2 = word2[ 1 ..] . to_string ( ) ;
23
+ if word1. chars ( ) . next ( ) . unwrap ( ) == word2. chars ( ) . next ( ) . unwrap ( ) {
24
+ return Solution :: min_distance ( w1. clone ( ) , w2. clone ( ) ) ;
25
+ }
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 ( )
16
30
}
17
31
}
18
32
You can’t perform that action at this time.
0 commit comments