From c9f008521c8b630de4a3ee8edb5f68f62884a531 Mon Sep 17 00:00:00 2001 From: EFanZh Date: Wed, 6 Nov 2024 22:38:54 +0800 Subject: [PATCH] Add problem 2309: Greatest English Letter in Upper and Lower Case --- src/lib.rs | 1 + .../iterative.rs | 31 +++++++++++++++++++ .../mod.rs | 18 +++++++++++ 3 files changed, 50 insertions(+) create mode 100644 src/problem_2309_greatest_english_letter_in_upper_and_lower_case/iterative.rs create mode 100644 src/problem_2309_greatest_english_letter_in_upper_and_lower_case/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 56ffcc55..29fda6fe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1714,6 +1714,7 @@ pub mod problem_2300_successful_pairs_of_spells_and_potions; pub mod problem_2302_count_subarrays_with_score_less_than_k; pub mod problem_2303_calculate_amount_paid_in_taxes; pub mod problem_2305_fair_distribution_of_cookies; +pub mod problem_2309_greatest_english_letter_in_upper_and_lower_case; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2309_greatest_english_letter_in_upper_and_lower_case/iterative.rs b/src/problem_2309_greatest_english_letter_in_upper_and_lower_case/iterative.rs new file mode 100644 index 00000000..58219324 --- /dev/null +++ b/src/problem_2309_greatest_english_letter_in_upper_and_lower_case/iterative.rs @@ -0,0 +1,31 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +use std::num::NonZeroU64; + +impl Solution { + pub fn greatest_letter(s: String) -> String { + let state = s.bytes().fold(0, |state, c| state | 1 << (c - b'A')); + + NonZeroU64::new(state & (state >> (b'a' - b'A'))).map_or(String::new(), |state| { + char::from(b'A' + 63 - state.leading_zeros() as u8).to_string() + }) + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn greatest_letter(s: String) -> String { + Self::greatest_letter(s) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2309_greatest_english_letter_in_upper_and_lower_case/mod.rs b/src/problem_2309_greatest_english_letter_in_upper_and_lower_case/mod.rs new file mode 100644 index 00000000..3403506b --- /dev/null +++ b/src/problem_2309_greatest_english_letter_in_upper_and_lower_case/mod.rs @@ -0,0 +1,18 @@ +pub mod iterative; + +pub trait Solution { + fn greatest_letter(s: String) -> String; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [("lEeTcOdE", "E"), ("arRAzFif", "R"), ("AbCdEfGhIjK", "")]; + + for (s, expected) in test_cases { + assert_eq!(S::greatest_letter(s.to_string()), expected); + } + } +}