|
| 1 | +/** |
| 2 | + * [1941] Check if All Characters Have Equal Number of Occurrences |
| 3 | + * |
| 4 | + * Given a string s, return true if s is a good string, or false otherwise. |
| 5 | + * A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency). |
| 6 | + * |
| 7 | + * Example 1: |
| 8 | + * |
| 9 | + * Input: s = "abacbc" |
| 10 | + * Output: true |
| 11 | + * Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s. |
| 12 | + * |
| 13 | + * Example 2: |
| 14 | + * |
| 15 | + * Input: s = "aaabb" |
| 16 | + * Output: false |
| 17 | + * Explanation: The characters that appear in s are 'a' and 'b'. |
| 18 | + * 'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times. |
| 19 | + * |
| 20 | + * |
| 21 | + * Constraints: |
| 22 | + * |
| 23 | + * 1 <= s.length <= 1000 |
| 24 | + * s consists of lowercase English letters. |
| 25 | + * |
| 26 | + */ |
| 27 | +pub struct Solution {} |
| 28 | + |
| 29 | +// problem: https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/ |
| 30 | +// discuss: https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/discuss/?currentPage=1&orderBy=most_votes&query= |
| 31 | + |
| 32 | +// submission codes start here |
| 33 | + |
| 34 | +impl Solution { |
| 35 | + pub fn are_occurrences_equal(s: String) -> bool { |
| 36 | + let hm: std::collections::HashMap<char, u32> = |
| 37 | + s.chars() |
| 38 | + .fold(std::collections::HashMap::new(), |mut hm, c| { |
| 39 | + *hm.entry(c).or_insert(0) += 1; |
| 40 | + hm |
| 41 | + }); |
| 42 | + |
| 43 | + let expected: &u32 = hm.get(&s.chars().next().unwrap()).unwrap(); |
| 44 | + |
| 45 | + hm.iter().all(|(_, count)| count == expected) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// submission codes end |
| 50 | + |
| 51 | +#[cfg(test)] |
| 52 | +mod tests { |
| 53 | + use super::*; |
| 54 | + |
| 55 | + #[test] |
| 56 | + fn test_1941_example_1() { |
| 57 | + let s = "abacbc".to_string(); |
| 58 | + |
| 59 | + let result = true; |
| 60 | + |
| 61 | + assert_eq!(Solution::are_occurrences_equal(s), result); |
| 62 | + } |
| 63 | + |
| 64 | + #[test] |
| 65 | + fn test_1941_example_2() { |
| 66 | + let s = "aaabb".to_string(); |
| 67 | + |
| 68 | + let result = false; |
| 69 | + |
| 70 | + assert_eq!(Solution::are_occurrences_equal(s), result); |
| 71 | + } |
| 72 | +} |
0 commit comments