Skip to content

Commit

Permalink
Add problem 1963: Minimum Number of Swaps to Make the String Balanced
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 22, 2023
1 parent e71ee71 commit 35b0ca9
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
@@ -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::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -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<S: Solution>() {
let test_cases = [("][][", 1), ("]]][[[", 2), ("[]", 0)];

for (s, expected) in test_cases {
assert_eq!(S::min_swaps(s.to_string()), expected);
}
}
}

0 comments on commit 35b0ca9

Please sign in to comment.