Skip to content

Latest commit

 

History

History
116 lines (92 loc) · 2.7 KB

File metadata and controls

116 lines (92 loc) · 2.7 KB

中文文档

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.

Solutions

Python3

class Solution:
    def areOccurrencesEqual(self, s: str) -> bool:
        cnt = Counter(s)
        return len(set(cnt.values())) == 1

Java

class Solution {
    public boolean areOccurrencesEqual(String s) {
        int[] cnt = new int[26];
        for (char c : s.toCharArray()) {
            ++cnt[c - 'a'];
        }
        int t = 0;
        for (int v : cnt) {
            if (v == 0) {
                continue;
            }
            if (t == 0) {
                t = v;
            } else if (t != v) {
                return false;
            }
        }
        return true;
    }
}

C++

class Solution {
public:
    bool areOccurrencesEqual(string s) {
        vector<int> cnt(26);
        for (char& c : s) ++cnt[c - 'a'];
        unordered_set<int> ss;
        for (int& v : cnt)
            if (v) ss.insert(v);
        return ss.size() == 1;
    }
};

Go

func areOccurrencesEqual(s string) bool {
	cnt := make([]int, 26)
	for _, c := range s {
		cnt[c-'a']++
	}
	ss := map[int]bool{}
	for _, v := range cnt {
		if v == 0 {
			continue
		}
		ss[v] = true
	}
	return len(ss) == 1
}

...