Formatted question description: https://leetcode.ca/all/1941.html

# 1941. Check if All Characters Have Equal Number of Occurrences

Easy

## Description

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.

## Solution

Use a hash map to store each character’s number of occurrences in s. The length of s should be divisible by the hash map’s size, and each character’s number of occurrences should be the same. In this case, return true. Otherwise, return false.

class Solution {
public boolean areOccurrencesEqual(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
int length = s.length();
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
int size = map.size();
if (length % size != 0)
return false;
int times = length / size;
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
int count = entry.getValue();
if (count != times)
return false;
}
return true;
}
}