diff --git a/rust/0332-reconstruct-itinerary.rs b/rust/0332-reconstruct-itinerary.rs new file mode 100644 index 000000000..0dc61de0f --- /dev/null +++ b/rust/0332-reconstruct-itinerary.rs @@ -0,0 +1,31 @@ +use std::cmp::Reverse; +use std::collections::{BinaryHeap, HashMap}; + +impl Solution { + pub fn find_itinerary(tickets: Vec>) -> Vec { + let mut graph: HashMap<&str, BinaryHeap>> = HashMap::new(); + for ticket in tickets.iter() { + graph + .entry(&ticket[0]) + .or_insert_with(BinaryHeap::new) + .push(Reverse(&ticket[1])); + } + let mut answer: Vec = Vec::with_capacity(tickets.len() + 1); + let mut stack: Vec<&str> = vec!["JFK"]; + while let Some(src) = stack.last() { + if let Some(dsts) = graph.get_mut(src) { + if !dsts.is_empty() { + if let Some(dst) = dsts.pop() { + stack.push(dst.0); + } + continue; + } + } + if let Some(last) = stack.pop() { + answer.push(last.to_string()); + } + } + answer.reverse(); + answer + } +}