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'
*/