From f1d54e2540886f2d1aa85508c9c6020626d41203 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sat, 7 Jun 2025 15:14:43 +0800 Subject: [PATCH] 20250607 finished. --- src/problem/mod.rs | 2 + ...lly_minimum_string_after_removing_stars.rs | 73 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 src/problem/p3170_lexicographically_minimum_string_after_removing_stars.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 275d192..5475797 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -696,3 +696,5 @@ 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; + +mod p3170_lexicographically_minimum_string_after_removing_stars; diff --git a/src/problem/p3170_lexicographically_minimum_string_after_removing_stars.rs b/src/problem/p3170_lexicographically_minimum_string_after_removing_stars.rs new file mode 100644 index 0000000..cc66cab --- /dev/null +++ b/src/problem/p3170_lexicographically_minimum_string_after_removing_stars.rs @@ -0,0 +1,73 @@ +/** + * [3170] Lexicographically Minimum String After Removing Stars + */ +pub struct Solution {} + +// submission codes start here +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +#[derive(Eq, PartialEq)] +struct CharacterPos { + char: u8, + pos: usize, +} + +impl Ord for CharacterPos { + fn cmp(&self, other: &Self) -> Ordering { + match other.char.cmp(&self.char) { + Ordering::Equal => self.pos.cmp(&other.pos), + Ordering::Greater => Ordering::Greater, + Ordering::Less => Ordering::Less, + } + } +} + +impl PartialOrd for CharacterPos { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Solution { + pub fn clear_stars(s: String) -> String { + // Use the binary head to store the minimal and nearest character. + let mut heap = BinaryHeap::new(); + // The array stores the tuple (character, is_removed). + let mut buffer: Vec<(u8, bool)> = s.bytes().map(|x| (x, false)).collect(); + + for (i, v) in s.bytes().enumerate() { + if v != b'*' { + heap.push(CharacterPos { char: v, pos: i }); + } else { + // Remove the star character firstly. + buffer.get_mut(i).unwrap().1 = true; + + // Then find the nearest and minimal character. + let head = heap.pop().unwrap(); + buffer.get_mut(head.pos).unwrap().1 = true; + } + } + + String::from_utf8( + buffer + .into_iter() + .filter_map(|(c, f)| if f { None } else { Some(c) }) + .collect(), + ) + .unwrap() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3170() { + assert_eq!("aab", Solution::clear_stars("aaba*".to_string())); + assert_eq!("abc", Solution::clear_stars("abc".to_string())); + } +}