From 1a424363704764c4ea51881733ebcc6dd581578e Mon Sep 17 00:00:00 2001 From: EFanZh Date: Sat, 13 Jan 2024 13:50:49 +0800 Subject: [PATCH] Add problem 2063: Vowels of All Substrings --- src/lib.rs | 1 + .../iterative.rs | 34 +++++++++++++++++++ .../mod.rs | 18 ++++++++++ 3 files changed, 53 insertions(+) create mode 100644 src/problem_2063_vowels_of_all_substrings/iterative.rs create mode 100644 src/problem_2063_vowels_of_all_substrings/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 516d2c94..7ae14ea9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1416,6 +1416,7 @@ pub mod problem_2043_simple_bank_system; pub mod problem_2047_number_of_valid_words_in_a_sentence; pub mod problem_2053_kth_distinct_string_in_an_array; pub mod problem_2057_smallest_index_with_equal_value; +pub mod problem_2063_vowels_of_all_substrings; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2063_vowels_of_all_substrings/iterative.rs b/src/problem_2063_vowels_of_all_substrings/iterative.rs new file mode 100644 index 00000000..70790b67 --- /dev/null +++ b/src/problem_2063_vowels_of_all_substrings/iterative.rs @@ -0,0 +1,34 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn count_vowels(word: String) -> i64 { + let mut result = 0; + let total = word.len() + 1; + + for (i, c) in (1..).zip(word.bytes()) { + if matches!(c, b'a' | b'e' | b'i' | b'o' | b'u') { + result += i * (total - i); + } + } + + result as _ + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn count_vowels(word: String) -> i64 { + Self::count_vowels(word) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2063_vowels_of_all_substrings/mod.rs b/src/problem_2063_vowels_of_all_substrings/mod.rs new file mode 100644 index 00000000..4edd3c0c --- /dev/null +++ b/src/problem_2063_vowels_of_all_substrings/mod.rs @@ -0,0 +1,18 @@ +pub mod iterative; + +pub trait Solution { + fn count_vowels(word: String) -> i64; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [("aba", 6), ("abc", 3), ("ltcd", 0)]; + + for (word, expected) in test_cases { + assert_eq!(S::count_vowels(word.to_string()), expected); + } + } +}