2278. Percentage of Letter in String Easy

@problem@discussion
#String



1/**
2 * [2278] Percentage of Letter in String
3 *
4 * Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent.
5 *  
6 * Example 1:
7 *
8 * Input: s = "foobar", letter = "o"
9 * Output: 33
10 * Explanation:
11 * The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.
12 *
13 * Example 2:
14 *
15 * Input: s = "jjjj", letter = "k"
16 * Output: 0
17 * Explanation:
18 * The percentage of characters in s that equal the letter 'k' is 0%, so we return 0.
19 *  
20 * Constraints:
21 *
22 * 1 <= s.length <= 100
23 * s consists of lowercase English letters.
24 * letter is a lowercase English letter.
25 *
26 */
27pub struct Solution {}
28
29// problem: https://leetcode.com/problems/percentage-of-letter-in-string/
30// discuss: https://leetcode.com/problems/percentage-of-letter-in-string/discuss/?currentPage=1&orderBy=most_votes&query=
31
32// submission codes start here
33
34impl Solution {
35    pub fn percentage_letter(s: String, letter: char) -> i32 {
36        s.chars()
37            .map(|x| if x == letter { 1 } else { 0 })
38            .sum::<i32>()
39            * 100
40            / s.len() as i32
41    }
42}
43
44// submission codes end
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn test_2278() {
52        assert_eq!(Solution::percentage_letter("foobar".into(), 'o'), 33);
53    }
54}
55


Back
© 2025 bowen.ge All Rights Reserved.