Input: s ="aaabb"Output: falseExplanation: 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.
A string is also valid if we can remove just 1 character at 1 index in the string, and the remaining characters will occur the same number of times. Given a string s, determine if it is valid. If so, return true, otherwise return false.
The key idea is that if all characters in the string appear the same number of times, then the set of their frequencies will have only one unique value. For example, in “abacbc”, ‘a’, ‘b’, and ‘c’ all appear 2 times, so the set of frequencies is {2}.
For the follow-up, check if removing one character can make all frequencies equal.
classSolution {
public:bool areOccurrencesEqual(string s) {
int freq[26] = {0};
for (char c : s) freq[c -'a']++;
int ans =0;
for (int i =0; i <26; ++i) {
if (freq[i] ==0) continue;
if (ans ==0) ans = freq[i];
elseif (freq[i] != ans) return false;
}
return true;
}
};
classSolution {
publicbooleanareOccurrencesEqual(String s) {
int[] freq =newint[26];
for (char c : s.toCharArray()) freq[c -'a']++;
int ans = 0;
for (int f : freq) {
if (f == 0) continue;
if (ans == 0) ans = f;
elseif (f != ans) returnfalse;
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funareOccurrencesEqual(s: String): Boolean {
val freq = IntArray(26)
for (c in s) freq[c - 'a']++var ans = 0for (f in freq) {
if (f ==0) continueif (ans ==0) ans = f
elseif (f != ans) returnfalse }
returntrue }
}
1
2
3
4
5
6
7
8
9
10
11
defareOccurrencesEqual(s: str) -> bool:
freq: dict[str, int] = {}
for c in s:
freq[c] = freq.get(c, 0) +1 ans =0for v in freq.values():
if ans ==0:
ans = v
elif v != ans:
returnFalsereturnTrue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnare_occurrences_equal(s: String) -> bool {
letmut freq = [0; 26];
for b in s.bytes() {
freq[(b -b'a') asusize] +=1;
}
letmut ans =0;
for&f in freq.iter() {
if f ==0 { continue; }
if ans ==0 { ans = f; }
elseif f != ans { returnfalse; }
}
true }
}
Count the frequency of each character using a hash map. If all frequencies are the same, the string is valid. This method is more general and works for any character set.