diff --git a/src/lib.rs b/src/lib.rs index 5479210c..d3724a41 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1695,6 +1695,7 @@ pub mod problem_2280_minimum_lines_to_represent_a_line_chart; pub mod problem_2283_check_if_number_has_equal_digit_count_and_digit_value; pub mod problem_2284_sender_with_largest_word_count; pub mod problem_2285_maximum_total_importance_of_roads; +pub mod problem_2287_rearrange_characters_to_make_target_string; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2287_rearrange_characters_to_make_target_string/iterative.rs b/src/problem_2287_rearrange_characters_to_make_target_string/iterative.rs new file mode 100644 index 00000000..adeca351 --- /dev/null +++ b/src/problem_2287_rearrange_characters_to_make_target_string/iterative.rs @@ -0,0 +1,47 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +use std::num::NonZeroU8; + +impl Solution { + pub fn rearrange_characters(s: String, target: String) -> i32 { + let mut s_counts = [0_u8; 26]; + + for c in s.into_bytes() { + s_counts[usize::from(c) - usize::from(b'a')] += 1; + } + + let mut target_counts = [0_u8; 26]; + + for c in target.into_bytes() { + target_counts[usize::from(c) - usize::from(b'a')] += 1; + } + + let mut result = u8::MAX; + + for (&c_count, &target_count) in s_counts.iter().zip(&target_counts) { + if let Some(target_count) = NonZeroU8::new(target_count) { + result = result.min(c_count / target_count); + } + } + + i32::from(result) + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn rearrange_characters(s: String, target: String) -> i32 { + Self::rearrange_characters(s, target) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2287_rearrange_characters_to_make_target_string/mod.rs b/src/problem_2287_rearrange_characters_to_make_target_string/mod.rs new file mode 100644 index 00000000..b2b010cf --- /dev/null +++ b/src/problem_2287_rearrange_characters_to_make_target_string/mod.rs @@ -0,0 +1,22 @@ +pub mod iterative; + +pub trait Solution { + fn rearrange_characters(s: String, target: String) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (("ilovecodingonleetcode", "code"), 2), + (("abcba", "abc"), 1), + (("abbaccaddaeea", "aaaaa"), 1), + ]; + + for ((s, target), expected) in test_cases { + assert_eq!(S::rearrange_characters(s.to_string(), target.to_string()), expected); + } + } +}