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: Hashtable
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Author: Huahua class Solution { public: bool areOccurrencesEqual(string s) { vector<int> m(26); int maxCount = 0; for (char c : s) maxCount = max(maxCount, ++m[c - 'a']); return all_of(begin(m), end(m), [maxCount](int c) -> bool { return c == 0 || c == maxCount; }); } }; |
Python3
1 2 3 4 |
# Author: Huahua class Solution: def areOccurrencesEqual(self, s: str) -> bool: return len(set(Counter(s).values())) == 1 |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment