diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 9b7bec2..275d192 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -694,3 +694,5 @@ mod p1298_maximum_candies_you_can_get_from_boxes; mod p3403_find_the_lexicographically_largest_string_from_the_box_i; mod p1061_lexicographically_smallest_equivalent_string; + +mod p2434_using_a_robot_to_print_the_lexicographically_smallest_string; diff --git a/src/problem/p2434_using_a_robot_to_print_the_lexicographically_smallest_string.rs b/src/problem/p2434_using_a_robot_to_print_the_lexicographically_smallest_string.rs new file mode 100644 index 0000000..757dc22 --- /dev/null +++ b/src/problem/p2434_using_a_robot_to_print_the_lexicographically_smallest_string.rs @@ -0,0 +1,59 @@ +/** + * [2434] Using a Robot to Print the Lexicographically Smallest String + */ +pub struct Solution {} + +// submission codes start here +use std::collections::HashMap; + +impl Solution { + pub fn robot_with_string(s: String) -> String { + let s: Vec = s.bytes().collect(); + let mut character_map = HashMap::new(); + + for &c in s.iter() { + let entry = character_map.entry(c).or_insert(0); + *entry += 1; + } + + // The Minimal value in the s. + let mut min_character = b'a'; + let mut result = Vec::with_capacity(s.len()); + let mut buffer = Vec::with_capacity(s.len()); + + for &c in s.iter() { + buffer.push(c); + *character_map.get_mut(&c).unwrap() -= 1; + + // Find the minimal value in the s. + while min_character != b'z' && character_map.get(&min_character).is_none_or(|x| *x == 0) + { + min_character += 1; + } + + while let Some(&head) = buffer.last() { + if head <= min_character { + result.push(head); + buffer.pop(); + } else { + break; + } + } + } + + String::from_utf8(result).unwrap() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2434() { + assert_eq!("azz", Solution::robot_with_string("zza".to_string())); + assert_eq!("abc", Solution::robot_with_string("bac".to_string())); + } +}