use std::collections::HashMap;
use std::default::Default;
#[derive(Default, Debug)]
pub struct Node {
pub children: HashMap<char, Node>,
pub terminal: bool,
}
impl Node {
pub fn new() -> Self {
Self::default()
}
pub fn add_suffix(&mut self, suffix: String) {
if let Some(first_char) = suffix.chars().next() {
let remaining_suffix = suffix[1..].to_string();
let child_node = self.children.entry(first_char).or_insert_with(Node::new);
child_node.add_suffix(remaining_suffix);
} else {
self.terminal = true;
}
}
pub fn find_by_prefix(&self, prefix: &str) -> Option<Vec<String>> {
if prefix.is_empty() {
return Some(self.collect_suffixes(""));
}
if let Some(first_char) = prefix.chars().next() {
if let Some(child) = self.children.get(&first_char) {
return child.find_by_prefix(&prefix[1..]);
}
}
None
}
fn collect_suffixes(&self, prefix: &str) -> Vec<String> {
let mut suffixes = Vec::new();
if self.terminal {
suffixes.push(prefix.to_string());
}
for (&ch, node) in &self.children {
let new_prefix = format!("{}{}", prefix, ch);
let mut child_suffixes = node.collect_suffixes(&new_prefix);
suffixes.append(&mut child_suffixes);
}
suffixes
}
}