longest prefix in the bag
This commit is contained in:
parent
94774010d0
commit
7ea5850800
2 changed files with 55 additions and 0 deletions
8
longest_common_prefix/Cargo.toml
Normal file
8
longest_common_prefix/Cargo.toml
Normal 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]
|
47
longest_common_prefix/src/main.rs
Normal file
47
longest_common_prefix/src/main.rs
Normal 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()]));
|
||||
}
|
Loading…
Reference in a new issue