Skip to content

Instantly share code, notes, and snippets.

@wperron
Created August 30, 2021 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wperron/6ec8a2ada1f302c2109632641dff7e20 to your computer and use it in GitHub Desktop.
Save wperron/6ec8a2ada1f302c2109632641dff7e20 to your computer and use it in GitHub Desktop.
Longest prefix in a list of strings
use std::collections::HashMap;
#[derive(Clone)]
pub struct Node {
end: bool,
next: HashMap<char, Node>,
}
pub struct Trie {
root: Node,
}
impl Trie {
pub fn new() -> Self {
Self {
root: Node {
end: false,
next: HashMap::new(),
},
}
}
pub fn insert(&mut self, s: String) {
let mut node = &mut self.root;
for c in s.chars() {
if !node.next.contains_key(&c) {
node.next.insert(
c,
Node {
end: false,
next: HashMap::new(),
},
);
}
node = node.next.get_mut(&c).unwrap();
}
node.end = true;
}
pub fn longest_prefix(strs: Vec<String>) -> String {
if strs.len() == 0 {
return String::from("");
}
if strs.len() == 1 {
return strs[0].clone();
}
let mut t = Self::new();
for s in &strs {
if s.len() == 0 {
return String::from("");
}
t.insert(s.to_string());
}
let mut max = 0;
let mut node = &t.root;
while node.next.len() == 1 && !node.end {
node = node.next.get(&strs[0].chars().nth(max).unwrap()).unwrap();
max += 1;
}
String::from(&strs[0][0..max])
}
}
fn main() {
let inputs: Vec<String> = vec![
"cranberry".to_string(),
"crawfish".to_string(),
"crap".to_string(),
];
println!("longest prefix: {}", Trie::longest_prefix(inputs));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment