2255. Count Prefixes of a Given String Easy

@problem@discussion
#Array#String



1/**
2 * [2255] Count Prefixes of a Given String
3 *
4 * You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.
5 * Return the number of strings in words that are a prefix of s.
6 * A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.
7 *  
8 * Example 1:
9 *
10 * Input: words = ["a","b","c","ab","bc","abc"], s = "abc"
11 * Output: 3
12 * Explanation:
13 * The strings in words which are a prefix of s = "abc" are:
14 * "a", "ab", and "abc".
15 * Thus the number of strings in words which are a prefix of s is 3.
16 * Example 2:
17 *
18 * Input: words = ["a","a"], s = "aa"
19 * Output: 2
20 * Explanation:
21 * Both of the strings are a prefix of s.
22 * Note that the same string can occur multiple times in words, and it should be counted each time.
23 *  
24 * Constraints:
25 *
26 * 1 <= words.length <= 1000
27 * 1 <= words[i].length, s.length <= 10
28 * words[i] and s consist of lowercase English letters only.
29 *
30 */
31pub struct Solution {}
32
33// problem: https://leetcode.com/problems/count-prefixes-of-a-given-string/
34// discuss: https://leetcode.com/problems/count-prefixes-of-a-given-string/discuss/?currentPage=1&orderBy=most_votes&query=
35
36// submission codes start here
37
38impl Solution {
39    pub fn count_prefixes(words: Vec<String>, s: String) -> i32 {
40        words.iter().filter(|w| s.starts_with(*w)).count() as i32
41    }
42}
43
44// submission codes end
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn test_2255_1() {
52        assert_eq!(Solution::count_prefixes(vec!("a".into(),"a".into()), "aa".into()), 2);
53        assert_eq!(Solution::count_prefixes(vec!("a".into(),"b".into(), "ab".into(), "abc".into()), "abc".into()), 3);
54    }
55}
56


Back
© 2025 bowen.ge All Rights Reserved.