14. Longest Common Prefix
Find the longest common prefix string amongst an array of strings.
Vertical scan approach:
#![allow(unused)]
fn main() {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
let first = strs[0].as_bytes();
for i in 0..first.len() {
for j in 1..strs.len() {
let sb = strs[j].as_bytes();
if i == sb.len() || first[i] != sb[i] {
return strs[0][..i].to_string();
}
}
}
strs[0].clone()
}
}
Sort approach (only first/last need comparing after sorting):
#![allow(unused)]
fn main() {
pub fn longest_common_prefix_sorted(strs: Vec<String>) -> String {
if strs.len() == 1 {
return strs[0].clone();
}
let mut strs = strs;
strs.sort();
let first = strs[0].as_bytes();
let last = strs[strs.len() - 1].as_bytes();
for i in 0..first.len() {
if first[i] != last[i] {
return strs[0][..i].to_string();
}
}
strs[0].clone()
}
}