Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. use std::cmp::{self, Ord};
  2.  
  3. pub fn levenshtein_distance(source: &str, target: &str) -> usize {
  4. if source.is_empty() || target.is_empty() {
  5. return 0;
  6. }
  7.  
  8. let source_chars: Vec<char> = source.chars().collect();
  9. let target_chars: Vec<char> = target.chars().collect();
  10.  
  11. let mut last_row: Vec<usize> = (0..=target.len()).collect();
  12.  
  13. for (i, source_char) in source_chars.iter().enumerate() {
  14. let mut next_dist = i + 1;
  15.  
  16. for (j, target_char) in target_chars.iter().enumerate() {
  17. let current_dist = next_dist;
  18.  
  19. let dist_if_substitute = if source_char == target_char {
  20. last_row[j]
  21. } else {
  22. last_row[j] + 1
  23. };
  24.  
  25. let dist_if_insert = current_dist + 1;
  26. let dist_if_delete = last_row[j + 1] + 1;
  27.  
  28. next_dist = min_3(dist_if_substitute, dist_if_insert, dist_if_delete);
  29.  
  30. last_row[j] = current_dist;
  31. }
  32.  
  33. last_row[target.len()] = next_dist;
  34. }
  35.  
  36. last_row[target.len()]
  37. }
  38.  
  39. fn min_3<T: Ord>(a: T, b: T, c: T) -> T {
  40. cmp::min(a, cmp::min(b, c))
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement