Skip to content

Commit 6978cd3

Browse files
committed
add solution
1 parent af80ca6 commit 6978cd3

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

edit_distance/src/lib.rs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,21 @@ struct Solution {}
1212

1313
impl Solution {
1414
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()
1630
}
1731
}
1832

0 commit comments

Comments
 (0)