longest prefix in the bag

This commit is contained in:
Joe Ardent 2022-10-25 19:36:44 -07:00
parent 94774010d0
commit 7ea5850800
2 changed files with 55 additions and 0 deletions

View File

@ -0,0 +1,8 @@
[package]
name = "longest_common_prefix"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@ -0,0 +1,47 @@
pub fn longest_common_prefix(strs: Vec<String>) -> String {
let mut s = String::from("");
let mut i = 0;
let mut same = true;
while same {
if let Some(first) = &strs[0].chars().nth(i) {
for st in &strs {
if let Some(c) = st.chars().nth(i) {
if c != *first {
same = false;
break;
}
} else {
same = false;
break;
}
}
i += 1;
if same {
s.push(*first);
}
} else {
break;
}
}
s
}
fn main() {
let res = longest_common_prefix(vec![
"flower".to_string(),
"flow".to_string(),
"flight".to_string(),
]);
dbg!(res);
let res = longest_common_prefix(vec![
"dog".to_string(),
"racecar".to_string(),
"car".to_string(),
]);
dbg!(res);
dbg!(longest_common_prefix(vec!["".to_string()]));
}