1941. Check if All Characters Have Equal Number of Occurrences

Given a string s, return true if s is a good string, or false otherwise.

A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).

 

Example 1:

Input: s = "abacbc"
Output: true
Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.

Example 2:

Input: s = "aaabb"
Output: false
Explanation: The characters that appear in s are 'a' and 'b'.
'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.

 

Constraints:

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters.

1941. Check if All Characters Have Equal Number of Occurrences
struct Solution;

use std::collections::HashMap;
use std::collections::HashSet;

impl Solution {
    fn are_occurrences_equal(s: String) -> bool {
        let mut hm: HashMap<char, usize> = HashMap::new();
        for c in s.chars() {
            *hm.entry(c).or_default() += 1;
        }
        let mut hs: HashSet<usize> = HashSet::new();
        for v in hm.values() {
            hs.insert(*v);
        }
        hs.len() == 1
    }
}

#[test]
fn test() {
    let s = "abacbc".to_string();
    let res = true;
    assert_eq!(Solution::are_occurrences_equal(s), res);
    let s = "aaabb".to_string();
    let res = false;
    assert_eq!(Solution::are_occurrences_equal(s), res);
}