File tree Expand file tree Collapse file tree 4 files changed +88
-0
lines changed
go/intersectionOfMultipleArrays/checkIfAllCharactersHaveEqualNumberOfOccurrences Expand file tree Collapse file tree 4 files changed +88
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 1942. Check if all characters have equal number of occurrences
2
+
3
+ Given a string s, return true if s is a good string, or false otherwise.
4
+
5
+ A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).
6
+
7
+
8
+
9
+ Example 1:
10
+
11
+ Input: s = "abacbc"
12
+ Output: true
13
+ Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
14
+
15
+
16
+ Example 2:
17
+
18
+ Input: s = "aaabb"
19
+ Output: false
20
+ Explanation: The characters that appear in s are 'a' and 'b'.
21
+ 'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.
22
+
23
+
24
+ Constraints:
25
+
26
+ 1 <= s.length <= 1000
27
+ s consists of lowercase English letters.
Original file line number Diff line number Diff line change
1
+ module checkIfAllCharactersHaveEqualNumberOfOccurrences
2
+
3
+ go 1.23.2
Original file line number Diff line number Diff line change
1
+ package solution
2
+
3
+ func areOccurrencesEqual (s string ) bool {
4
+ // create a map to store counts of all runes in s.
5
+ runeMap := make (map [rune ]int )
6
+
7
+ // add all runes in the stirng to runeMap.
8
+ for _ , r := range s {
9
+ runeMap [r ]++
10
+ }
11
+
12
+ // grab the count of the first character in s as the sentinel to check.
13
+ sentinel := runeMap [rune (s [0 ])]
14
+
15
+ // loop through the runeMap to check the rune counts.
16
+ for _ , v := range runeMap {
17
+ // if we find any value that is not the same then all runes in the
18
+ // string do not have equal occurrences, return false.
19
+ if v != sentinel {
20
+ return false
21
+ }
22
+ }
23
+
24
+ // did not find a rune with a different count, return true.
25
+ return true
26
+ }
Original file line number Diff line number Diff line change
1
+ package solution
2
+
3
+ import "testing"
4
+
5
+ func TestAreOccurrencesEqual (t * testing.T ) {
6
+ testCases := []struct {
7
+ name string
8
+ s string
9
+ want bool
10
+ }{
11
+ {
12
+ name : "test case one" ,
13
+ s : "abacbc" ,
14
+ want : true ,
15
+ },
16
+ {
17
+ name : "test case two" ,
18
+ s : "aaabb" ,
19
+ want : false ,
20
+ },
21
+ }
22
+
23
+ for _ , tc := range testCases {
24
+ t .Run (tc .name , func (t * testing.T ) {
25
+ got := areOccurrencesEqual (tc .s )
26
+
27
+ if got != tc .want {
28
+ t .Errorf ("got %v, want %v" , got , tc .want )
29
+ }
30
+ })
31
+ }
32
+ }
You can’t perform that action at this time.
0 commit comments