Skip to content

Latest commit

 

History

History
 
 

1941. Check if All Characters Have Equal Number of Occurrences

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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 1.

// OJ: https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(C) where C is the range of the characters
class Solution {
public:
    bool areOccurrencesEqual(string s) {
        int cnt[26] = {}, mx = 0;
        for (char c : s) {
            mx = max(mx, ++cnt[c - 'a']);
        }
        for (int i = 0; i < 26; ++i) {
            if (cnt[i] && cnt[i] != mx) return false;
        }
        return true;
    }
};