From 8285dd6654c1d4ad55e7da69a8a3b0c655e0239f Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 17 Mar 2025 12:02:00 +0800 Subject: [PATCH] 20250317 finished. --- src/problem/mod.rs | 2 + ...er_of_swaps_to_make_the_string_balanced.rs | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/problem/p1963_minimum_number_of_swaps_to_make_the_string_balanced.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 8e09550..9944a92 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -542,3 +542,5 @@ mod p3340_check_balanced_string; mod p3110_score_of_a_string; mod p2272_substring_with_largest_variance; + +mod p1963_minimum_number_of_swaps_to_make_the_string_balanced; diff --git a/src/problem/p1963_minimum_number_of_swaps_to_make_the_string_balanced.rs b/src/problem/p1963_minimum_number_of_swaps_to_make_the_string_balanced.rs new file mode 100644 index 0000000..e3bc98d --- /dev/null +++ b/src/problem/p1963_minimum_number_of_swaps_to_make_the_string_balanced.rs @@ -0,0 +1,40 @@ +/** + * [1963] Minimum Number of Swaps to Make the String Balanced + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn min_swaps(s: String) -> i32 { + let mut count = 0; + let mut min_count = 0; + + for c in s.chars() { + match c { + '[' => count += 1, + ']' => { + count -= 1; + min_count = min_count.min(count) + } + _ => {} + } + } + + (-min_count + 1) / 2 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1963() { + assert_eq!(1, Solution::min_swaps("][][".to_owned())); + assert_eq!(2, Solution::min_swaps("]]][[[".to_owned())); + assert_eq!(0, Solution::min_swaps("[]".to_owned())); + } +}