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.

40,276 questions

52,302 answers

573 users

How to find the longest common prefix of all the words in a string with Rust

1 Answer

0 votes
use regex::Regex;

fn longest_common_prefix(input: &str) -> String {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return String::new();
    }

    // Split by non‑word characters (Rust-safe version of \W+)
    let re = Regex::new(r"[^A-Za-z0-9_]+").unwrap();
    let words: Vec<String> = re
        .split(&trimmed.to_lowercase())
        .filter(|w| !w.is_empty())
        .map(|w| w.to_string())
        .collect();

    if words.is_empty() {
        return String::new();
    }

    let mut prefix = words[0].clone();

    for word in &words {
        while !word.starts_with(&prefix) {
            prefix.pop();
            if prefix.is_empty() {
                return String::new();
            }
        }
    }

    prefix
}

fn main() {
    let s1 = "The lowly inhabitants of the lowland were surprised to see the lower branches.";
    println!("LCP: '{}'", longest_common_prefix(s1));

    let s2 = "unclear, uncertain, unexpected";
    println!("LCP: '{}'", longest_common_prefix(s2));
}




/*
run:

LCP: ''
LCP: 'un'

*/

 



answered 2 days ago by avibootz

Related questions

...