Skip to content

Commit 179ad29

Browse files
committed
1941. Check if All Characters Have Equal Number of Occurrences: AC
1 parent 8bf648a commit 179ad29

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

Diff for: src/solution/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1462,3 +1462,4 @@ mod s1935_maximum_number_of_words_you_can_type;
14621462
mod s1936_add_minimum_number_of_rungs;
14631463
mod s1937_maximum_number_of_points_with_cost;
14641464
mod s1938_maximum_genetic_difference_query;
1465+
mod s1941_check_if_all_characters_have_equal_number_of_occurrences;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* [1941] Check if All Characters Have Equal Number of Occurrences
3+
*
4+
* Given a string s, return true if s is a good string, or false otherwise.
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+
* Example 1:
8+
*
9+
* Input: s = "abacbc"
10+
* Output: true
11+
* Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
12+
*
13+
* Example 2:
14+
*
15+
* Input: s = "aaabb"
16+
* Output: false
17+
* Explanation: The characters that appear in s are 'a' and 'b'.
18+
* 'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.
19+
*
20+
*
21+
* Constraints:
22+
*
23+
* 1 <= s.length <= 1000
24+
* s consists of lowercase English letters.
25+
*
26+
*/
27+
pub struct Solution {}
28+
29+
// problem: https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/
30+
// discuss: https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/discuss/?currentPage=1&orderBy=most_votes&query=
31+
32+
// submission codes start here
33+
34+
impl Solution {
35+
pub fn are_occurrences_equal(s: String) -> bool {
36+
let hm: std::collections::HashMap<char, u32> =
37+
s.chars()
38+
.fold(std::collections::HashMap::new(), |mut hm, c| {
39+
*hm.entry(c).or_insert(0) += 1;
40+
hm
41+
});
42+
43+
let expected: &u32 = hm.get(&s.chars().next().unwrap()).unwrap();
44+
45+
hm.iter().all(|(_, count)| count == expected)
46+
}
47+
}
48+
49+
// submission codes end
50+
51+
#[cfg(test)]
52+
mod tests {
53+
use super::*;
54+
55+
#[test]
56+
fn test_1941_example_1() {
57+
let s = "abacbc".to_string();
58+
59+
let result = true;
60+
61+
assert_eq!(Solution::are_occurrences_equal(s), result);
62+
}
63+
64+
#[test]
65+
fn test_1941_example_2() {
66+
let s = "aaabb".to_string();
67+
68+
let result = false;
69+
70+
assert_eq!(Solution::are_occurrences_equal(s), result);
71+
}
72+
}

0 commit comments

Comments
 (0)