Skip to content

Commit

Permalink
Add problem 2185: Counting Words With a Given Prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Mar 13, 2024
1 parent 2faa3fd commit 4359563
Show file tree
Hide file tree
Showing 3 changed files with 52 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 @@ -1476,6 +1476,7 @@ pub mod problem_2161_partition_array_according_to_given_pivot;
pub mod problem_2165_smallest_value_of_the_rearranged_number;
pub mod problem_2166_design_bitset;
pub mod problem_2169_count_operations_to_obtain_zero;
pub mod problem_2185_counting_words_with_a_given_prefix;

#[cfg(test)]
mod test_utilities;
27 changes: 27 additions & 0 deletions src/problem_2185_counting_words_with_a_given_prefix/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn prefix_count(words: Vec<String>, pref: String) -> i32 {
let pref = pref.as_str();

words.iter().filter(|word| word.starts_with(pref)).count() as _
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn prefix_count(words: Vec<String>, pref: String) -> i32 {
Self::prefix_count(words, pref)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
24 changes: 24 additions & 0 deletions src/problem_2185_counting_words_with_a_given_prefix/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
pub mod iterative;

pub trait Solution {
fn prefix_count(words: Vec<String>, pref: String) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
((&["pay", "attention", "practice", "attend"], "at"), 2),
((&["leetcode", "win", "loops", "success"], "code"), 0),
];

for ((words, pref), expected) in test_cases {
assert_eq!(
S::prefix_count(words.iter().copied().map(str::to_string).collect(), pref.to_string()),
expected,
);
}
}
}

0 comments on commit 4359563

Please sign in to comment.