|
| 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