From 38820059945435690d0efe89c5c5d74e7511b079 Mon Sep 17 00:00:00 2001 From: Bauke Date: Wed, 6 Apr 2022 15:04:41 +0200 Subject: [PATCH] Solve longest-common-prefix. --- source/lib.rs | 1 + source/longest_common_prefix/mod.rs | 71 +++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 source/longest_common_prefix/mod.rs diff --git a/source/lib.rs b/source/lib.rs index 1b37410..b7992e7 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -1,3 +1,4 @@ +pub mod longest_common_prefix; pub mod palindrome_number; pub mod reverse_integer; pub mod two_sum; diff --git a/source/longest_common_prefix/mod.rs b/source/longest_common_prefix/mod.rs new file mode 100644 index 0000000..05594ca --- /dev/null +++ b/source/longest_common_prefix/mod.rs @@ -0,0 +1,71 @@ +pub fn longest_common_prefix(strings: Vec) -> String { + // Sort the strings ascending by length. + let mut strings = strings.clone(); + strings.sort_by(|a, b| a.len().cmp(&b.len())); + + // Then grab the shortest string. + let shortest_string = match strings.first() { + Some(string) => string, + None => return String::new(), + }; + + // The shortest string must be the maximum possible prefix, so start with it. + let mut prefix = shortest_string.clone(); + + // Then loop over the shortest string's length and check if every string in + // the list starts with the prefix, and if they don't, pop the last character + // from the prefix. + for _ in 0..shortest_string.len() { + // If we find a prefix that all strings start with, we've found the longest + // common one. + if strings.iter().all(|string| string.starts_with(&prefix)) { + break; + } else { + prefix.pop(); + } + } + + // If by the end there is no longest common prefix, the prefix will be an + // empty string. + prefix +} + +#[test] +fn test_longest_common_prefix() { + assert_eq!( + longest_common_prefix(vec![ + "doggo".to_string(), + "doggie".to_string(), + "dog".to_string(), + ]), + "dog" + ); + + assert_eq!( + longest_common_prefix(vec![ + "flower".to_string(), + "flow".to_string(), + "flight".to_string(), + ]), + "fl" + ); + + assert_eq!( + longest_common_prefix(vec![ + "dog".to_string(), + "racecar".to_string(), + "car".to_string(), + ]), + "" + ); + + assert_eq!( + longest_common_prefix(vec![ + "dog".to_string(), + "racecar".to_string(), + "car".to_string(), + "".to_string() + ]), + "" + ); +}