1
Fork 0
leetcode/source/longest_common_prefix/mod.rs

31 lines
970 B
Rust
Raw Permalink Normal View History

2022-04-08 21:00:38 +00:00
pub fn longest_common_prefix(mut strings: Vec<String>) -> String {
2022-04-06 13:04:41 +00:00
// Sort the strings ascending by length.
2022-04-08 21:00:38 +00:00
strings.sort_by_key(|a| a.len());
2022-04-06 13:04:41 +00:00
// 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
}