Skip to content

Instantly share code, notes, and snippets.

@shadiakiki1986
Last active January 13, 2020 07:51
Show Gist options
  • Save shadiakiki1986/0cde15d6d229dfd1fe10e6af8ecaa3e4 to your computer and use it in GitHub Desktop.
Save shadiakiki1986/0cde15d6d229dfd1fe10e6af8ecaa3e4 to your computer and use it in GitHub Desktop.
Trying out string longest common prefix https://beta.rustgym.com/longest-common-prefix/

Instructions

  • cargo new test-rustgym-longestcommonprefix
  • cd 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!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment