Skip to content

Commit dcc78c8

Browse files
committed
2185. Counting Words With a Given Prefix: AC
1 parent 27fea98 commit dcc78c8

2 files changed

Lines changed: 73 additions & 0 deletions

File tree

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1651,3 +1651,4 @@ mod s2180_count_integers_with_even_digit_sum;
16511651
mod s2181_merge_nodes_in_between_zeros;
16521652
mod s2182_construct_string_with_repeat_limit;
16531653
mod s2183_count_array_pairs_divisible_by_k;
1654+
mod s2185_counting_words_with_a_given_prefix;
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* [2185] Counting Words With a Given Prefix
3+
*
4+
* You are given an array of strings words and a string pref.
5+
* Return the number of strings in words that contain pref as a prefix.
6+
* A prefix of a string s is any leading contiguous substring of s.
7+
*
8+
* Example 1:
9+
*
10+
* Input: words = ["pay","<u>at</u>tention","practice","<u>at</u>tend"], pref = "at"
11+
* Output: 2
12+
* Explanation: The 2 strings that contain "at" as a prefix are: "<u>at</u>tention" and "<u>at</u>tend".
13+
*
14+
* Example 2:
15+
*
16+
* Input: words = ["leetcode","win","loops","success"], pref = "code"
17+
* Output: 0
18+
* Explanation: There are no strings that contain "code" as a prefix.
19+
*
20+
*
21+
* Constraints:
22+
*
23+
* 1 <= words.length <= 100
24+
* 1 <= words[i].length, pref.length <= 100
25+
* words[i] and pref consist of lowercase English letters.
26+
*
27+
*/
28+
pub struct Solution {}
29+
30+
// problem: https://leetcode.com/problems/counting-words-with-a-given-prefix/
31+
// discuss: https://leetcode.com/problems/counting-words-with-a-given-prefix/discuss/?currentPage=1&orderBy=most_votes&query=
32+
33+
// submission codes start here
34+
35+
impl Solution {
36+
pub fn prefix_count(words: Vec<String>, pref: String) -> i32 {
37+
words.into_iter().fold(0, |s, w| {
38+
s + if pref.len() <= w.len() && w.chars().zip(pref.chars()).all(|(c1, c2)| c1 == c2) {
39+
1
40+
} else {
41+
0
42+
}
43+
})
44+
}
45+
}
46+
47+
// submission codes end
48+
49+
#[cfg(test)]
50+
mod tests {
51+
use super::*;
52+
53+
#[test]
54+
fn test_2185_example_1() {
55+
let words = vec_string!["pay", "attention", "practice", "attend"];
56+
let pref = "at".to_string();
57+
58+
let result = 2;
59+
60+
assert_eq!(Solution::prefix_count(words, pref), result);
61+
}
62+
63+
#[test]
64+
fn test_2185_example_2() {
65+
let words = vec_string!["leetcode", "win", "loops", "success"];
66+
let pref = "code".to_string();
67+
68+
let result = 0;
69+
70+
assert_eq!(Solution::prefix_count(words, pref), result);
71+
}
72+
}

0 commit comments

Comments
 (0)