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).
LeetCode Problem - 1941
class Solution {
public boolean areOccurrencesEqual(String s) {
// Initialize a map to store the frequency of each character
Map<Character, Integer> map = new HashMap<>();
// Iterate over each character in the string
for(char c : s.toCharArray()) {
// Update the frequency of each character in the map
map.put(c, map.getOrDefault(c, 0) + 1);
}
// Get the frequency of the first character as a reference
int flag = map.get(s.charAt(0));
// Iterate over the frequencies of all characters in the map
for(int e : map.values()) {
// If any character's frequency does not match the reference, return false
if(flag != e) return false;
}
// If all characters have the same frequency, return true
return true;
}
}