Skip to content

Commit

Permalink
Add problem 2405: Optimal Partition of String
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jan 22, 2025
1 parent 741ea79 commit 30624a5
Show file tree
Hide file tree
Showing 3 changed files with 66 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 @@ -1791,6 +1791,7 @@ pub mod problem_2400_number_of_ways_to_reach_a_position_after_exactly_k_steps;
pub mod problem_2401_longest_nice_subarray;
pub mod problem_2402_meeting_rooms_iii;
pub mod problem_2404_most_frequent_even_element;
pub mod problem_2405_optimal_partition_of_string;

#[cfg(test)]
mod test_utilities;
47 changes: 47 additions & 0 deletions src/problem_2405_optimal_partition_of_string/bit_manipulation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
pub struct Solution;

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

impl Solution {
pub fn partition_string(s: String) -> i32 {
let mut iter = s.bytes();
let mut c = iter.next().unwrap();
let mut used = 0_u32;
let mut result = 1;

loop {
let probe = 1 << (c - b'a');

if used & probe == 0 {
used |= probe;
} else {
result += 1;
used = probe;
}

if let Some(next) = iter.next() {
c = next;
} else {
break;
}
}

result
}
}

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

impl super::Solution for Solution {
fn partition_string(s: String) -> i32 {
Self::partition_string(s)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_2405_optimal_partition_of_string/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod bit_manipulation;

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

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

pub fn run<S: Solution>() {
let test_cases = [("abacaba", 4), ("ssssss", 6)];

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

0 comments on commit 30624a5

Please sign in to comment.