Skip to content

Commit

Permalink
Add problem 1864: Minimum Number of Swaps to Make the Binary String A…
Browse files Browse the repository at this point in the history
…lternating
  • Loading branch information
EFanZh committed Oct 8, 2023
1 parent cfe797b commit 05b5862
Show file tree
Hide file tree
Showing 3 changed files with 63 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 @@ -1439,6 +1439,7 @@ pub mod problem_1855_maximum_distance_between_a_pair_of_values;
pub mod problem_1859_sorting_the_sentence;
pub mod problem_1860_incremental_memory_leak;
pub mod problem_1861_rotating_the_box;
pub mod problem_1864_minimum_number_of_swaps_to_make_the_binary_string_alternating;
pub mod problem_1869_longer_contiguous_segments_of_ones_than_zeros;

#[cfg(test)]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
fn fold_count(count: u16, c: u8) -> u16 {
count + u16::from(c) - u16::from(b'0')
}

pub fn min_swaps(s: String) -> i32 {
let n = s.len() as u16;
let ones = s.bytes().fold(0, Self::fold_count);
let zeros = n - ones;
let diff_plus_1 = (ones + 1).wrapping_sub(zeros);

if diff_plus_1 < 3 {
let even_ones = s.bytes().step_by(2).fold(0, Self::fold_count);

i32::from(match diff_plus_1 {
0 => even_ones,
1 => even_ones.min((n + 1) / 2 - even_ones),
_ => (n + 1) / 2 - even_ones,
})
} else {
-1
}
}
}

// ------------------------------------------------------ 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 greedy;

pub trait Solution {
fn min_swaps(s: String) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [("111000", 1), ("010", 0), ("1110", -1), ("1", 0)];

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

0 comments on commit 05b5862

Please sign in to comment.