From 35b0ca9eba6ac52f6e2164d1c0a3a69fd199f419 Mon Sep 17 00:00:00 2001 From: EFanZh Date: Wed, 22 Nov 2023 20:21:30 +0800 Subject: [PATCH] Add problem 1963: Minimum Number of Swaps to Make the String Balanced --- src/lib.rs | 1 + .../iterative.rs | 37 +++++++++++++++++++ .../mod.rs | 18 +++++++++ 3 files changed, 56 insertions(+) create mode 100644 src/problem_1963_minimum_number_of_swaps_to_make_the_string_balanced/iterative.rs create mode 100644 src/problem_1963_minimum_number_of_swaps_to_make_the_string_balanced/mod.rs diff --git a/src/lib.rs b/src/lib.rs index bf769b5b..f127b44b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1362,6 +1362,7 @@ pub mod problem_1952_three_divisors; pub mod problem_1957_delete_characters_to_make_fancy_string; pub mod problem_1961_check_if_string_is_a_prefix_of_array; pub mod problem_1962_remove_stones_to_minimize_the_total; +pub mod problem_1963_minimum_number_of_swaps_to_make_the_string_balanced; pub mod problem_1967_number_of_strings_that_appear_as_substrings_in_word; pub mod problem_1968_array_with_elements_not_equal_to_average_of_neighbors; diff --git a/src/problem_1963_minimum_number_of_swaps_to_make_the_string_balanced/iterative.rs b/src/problem_1963_minimum_number_of_swaps_to_make_the_string_balanced/iterative.rs new file mode 100644 index 00000000..c654f820 --- /dev/null +++ b/src/problem_1963_minimum_number_of_swaps_to_make_the_string_balanced/iterative.rs @@ -0,0 +1,37 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn min_swaps(s: String) -> i32 { + let mut stack = 0_u32; + + for c in s.into_bytes() { + stack = stack.wrapping_add(if c == b'[' { + 1 + } else if stack == 0 { + 0 + } else { + u32::MAX + }); + } + + ((stack + 1) / 2) as _ + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn min_swaps(s: String) -> i32 { + Self::min_swaps(s) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_1963_minimum_number_of_swaps_to_make_the_string_balanced/mod.rs b/src/problem_1963_minimum_number_of_swaps_to_make_the_string_balanced/mod.rs new file mode 100644 index 00000000..e7b12083 --- /dev/null +++ b/src/problem_1963_minimum_number_of_swaps_to_make_the_string_balanced/mod.rs @@ -0,0 +1,18 @@ +pub mod iterative; + +pub trait Solution { + fn min_swaps(s: String) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [("][][", 1), ("]]][[[", 2), ("[]", 0)]; + + for (s, expected) in test_cases { + assert_eq!(S::min_swaps(s.to_string()), expected); + } + } +}