1941. Check if All Characters Have Equal Number of Occurrences

1941. Check if All Characters Have Equal Number of Occurrences

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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.

Difficulty : Easy

Solution

Use int[26] to store the # of occurrences for each character

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public boolean areOccurrencesEqual(String s) {
int[] counts = new int[26];
char[] array = s.toCharArray();
for (char c : array) {
counts[c-'a']++;
}
int cnt = counts[array[0] - 'a'];
for (int i = 0; i < 26; i++) {
if (counts[i] != 0 && counts[i] != cnt) {
return false;
}
}
return true;
}
}