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.

Approach

Java

public class EqualOccurrences {
    public static void main(String[] args) {

        String s = "abacbc";

        System.out.println(areOccurrencesEqual(s));
    }

    static boolean areOccurrencesEqual(String s) {

        int freq[] = new int[26];

        // count frequency of each characters in the
        // string
        for (int i = 0; i < s.length(); i++) {
            freq[s.charAt(i) - 'a']++;
        }
        int cnt = Integer.MAX_VALUE;

        for (int i = 0; i < 26; i++) {
            if (freq[i] > 0) {
                if (cnt == Integer.MAX_VALUE)
                    cnt = freq[i];
                else {
                    if (freq[i] != cnt)
                        return false;
                }
            }
        }
        return true;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

bool areOccurrencesEqual(string s)
{

    int freq[26] = {0};

    //coutt frequency of each characters in the
    //string
    for (int i = 0i < s.size(); i++)
    {
        freq[s[i] - 'a']++;
    }
    int cnt = INT_MAX;

    for (int i = 0i < 26i++)
    {
        if (freq[i] > 0)
        {
            if (cnt == INT_MAX)
                cnt = freq[i];
            else
            {
                if (freq[i] != cnt)
                    return false;
            }
        }
    }
    return true;
}
int main()
{
    string s = "abacbc";

    if (areOccurrencesEqual(s))
        cout << "true\n";

    else
        cout << "false\n";

    return 0;
}


No comments:

Post a Comment