-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add problem 2185: Counting Words With a Given Prefix
- Loading branch information
Showing
3 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
27 changes: 27 additions & 0 deletions
27
src/problem_2185_counting_words_with_a_given_prefix/iterative.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
24
src/problem_2185_counting_words_with_a_given_prefix/mod.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
); | ||
} | ||
} | ||
} |