From 243613806077edd579fe0eb88749c99a670fb9ac Mon Sep 17 00:00:00 2001 From: EFanZh Date: Fri, 8 Nov 2024 23:19:24 +0800 Subject: [PATCH] Add problem 2315: Count Asterisks --- src/lib.rs | 1 + src/problem_2315_count_asterisks/iterative.rs | 42 +++++++++++++++++++ src/problem_2315_count_asterisks/mod.rs | 22 ++++++++++ 3 files changed, 65 insertions(+) create mode 100644 src/problem_2315_count_asterisks/iterative.rs create mode 100644 src/problem_2315_count_asterisks/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 17c70e37..de8120a9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1716,6 +1716,7 @@ 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; pub mod problem_2310_sum_of_numbers_with_units_digit_k; +pub mod problem_2315_count_asterisks; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2315_count_asterisks/iterative.rs b/src/problem_2315_count_asterisks/iterative.rs new file mode 100644 index 00000000..da381f12 --- /dev/null +++ b/src/problem_2315_count_asterisks/iterative.rs @@ -0,0 +1,42 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn count_asterisks(s: String) -> i32 { + let mut result = 0; + let mut iter = s.bytes(); + + loop { + loop { + if let Some(c) = iter.next() { + if c == b'|' { + break; + } + + result += i32::from(c == b'*'); + } else { + return result; + } + } + + iter.find(|&c| c == b'|'); + } + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn count_asterisks(s: String) -> i32 { + Self::count_asterisks(s) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2315_count_asterisks/mod.rs b/src/problem_2315_count_asterisks/mod.rs new file mode 100644 index 00000000..b4842aa1 --- /dev/null +++ b/src/problem_2315_count_asterisks/mod.rs @@ -0,0 +1,22 @@ +pub mod iterative; + +pub trait Solution { + fn count_asterisks(s: String) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + ("l|*e*et|c**o|*de|", 2), + ("iamprogrammer", 0), + ("yo|uar|e**|b|e***au|tifu|l", 5), + ]; + + for (s, expected) in test_cases { + assert_eq!(S::count_asterisks(s.to_string()), expected); + } + } +}