Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to find the longest common string prefix in an array of strings with Rust

1 Answer

0 votes
fn longest_common_prefix(lst: &mut Vec<&str>) -> String {
    let size = lst.len();
    
    if size == 0 {
        return "".to_string();
    }
    if size == 1 {
        return lst[0].to_string();
    }
    
    lst.sort();
    
    let min_length = std::cmp::min(lst[0].len(), lst[size - 1].len());
    let mut i = 0;
    while i < min_length && lst[0].as_bytes()[i] == lst[size - 1].as_bytes()[i] {
        i += 1;
    }
    
    lst[0][0..i].to_string()
}

fn main() {
    let mut lst = vec!["programmer", "programming", "professional", "programmables"];
    
    println!("{}", longest_common_prefix(&mut lst));
}


  
/*
run:

pro
  
*/

 



answered Aug 29, 2024 by avibootz
...