Instructions
cargo new test-rustgym-longestcommonprefixcd test-rustgym-longestcommonprefix- copy src/main.rs from below file
cargo test
| use std::str::Chars; | |
| // copied from https://beta.rustgym.com/longest-common-prefix/ | |
| fn longest_common_prefix(strs: Vec<String>) -> String { | |
| let mut prefix = String::new(); | |
| let mut iters: Vec<Chars> = strs.iter().map(|s| {s.chars()}).collect(); | |
| let mut curr_char: Option<char> = None; | |
| if strs.len() < 1 { return prefix } | |
| loop { | |
| curr_char.take().map(|ch| prefix.push(ch)); | |
| for iter in iters.iter_mut() { | |
| let mut ch = iter.next(); | |
| if ch.is_none() { return prefix } | |
| match curr_char { | |
| None => curr_char = ch.take(), | |
| Some(curr) => { | |
| if curr != ch.unwrap() { | |
| return prefix | |
| } | |
| }, | |
| } | |
| } | |
| } | |
| } | |
| #[test] | |
| fn test_lcp() { | |
| let input_1: Vec<&str> = vec!["hello", "hi", "hey"]; | |
| let input_2: Vec<String> = input_1.iter().map(|s| s.to_string()).collect(); | |
| let actual = longest_common_prefix(input_2); | |
| let expected = "h"; | |
| assert_eq!(expected, actual); | |
| } | |
| fn main() { | |
| println!("Hello, world!"); | |
| } |