Skip to content

Commit

Permalink
Add problem 2287: Rearrange Characters to Make Target String
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Oct 18, 2024
1 parent c05c2a8 commit f24b928
Show file tree
Hide file tree
Showing 3 changed files with 70 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 @@ -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;
Original file line number Diff line number Diff line change
@@ -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::<super::Solution>();
}
}
22 changes: 22 additions & 0 deletions src/problem_2287_rearrange_characters_to_make_target_string/mod.rs
Original file line number Diff line number Diff line change
@@ -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<S: Solution>() {
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);
}
}
}

0 comments on commit f24b928

Please sign in to comment.