Skip to content

Commit b504a82

Browse files
committed
Add problem 2085: Count Common Words With One Occurrence
1 parent fa7a464 commit b504a82

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,7 @@ pub mod problem_1961_check_if_string_is_a_prefix_of_array;
642642
pub mod problem_1962_remove_stones_to_minimize_the_total;
643643
pub mod problem_2000_reverse_prefix_of_word;
644644
pub mod problem_2032_two_out_of_three;
645+
pub mod problem_2085_count_common_words_with_one_occurrence;
645646
pub mod problem_2108_find_first_palindromic_string_in_the_array;
646647
pub mod problem_2138_divide_a_string_into_groups_of_size_k;
647648
pub mod problem_2348_number_of_zero_filled_subarrays;
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
pub struct Solution;
2+
3+
use std::collections::HashMap;
4+
5+
impl Solution {
6+
pub fn count_words(words1: Vec<String>, words2: Vec<String>) -> i32 {
7+
let mut result = 0;
8+
9+
let mut map1 = HashMap::with_capacity(words1.len());
10+
let mut map2 = HashMap::with_capacity(words2.len());
11+
12+
for word in &words1 {
13+
*map1.entry(word).or_insert(0) += 1;
14+
}
15+
for word in &words2 {
16+
*map2.entry(word).or_insert(0) += 1;
17+
}
18+
19+
for word in &words1 {
20+
result += i32::from(map1.get(word) == Some(&1) && map2.get(word) == Some(&1));
21+
}
22+
result
23+
}
24+
}
25+
26+
impl super::Solution for Solution {
27+
fn count_words(words1: Vec<String>, words2: Vec<String>) -> i32 {
28+
Self::count_words(words1, words2)
29+
}
30+
}
31+
32+
#[cfg(test)]
33+
mod tests {
34+
#[test]
35+
fn test_solution() {
36+
super::super::tests::run::<super::Solution>();
37+
}
38+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
pub mod hash_map;
2+
3+
pub trait Solution {
4+
fn count_words(words1: Vec<String>, words2: Vec<String>) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [
13+
(
14+
(
15+
&["leetcode", "is", "amazing", "as", "is"] as &[_],
16+
&["amazing", "leetcode", "is"] as &[_],
17+
),
18+
2,
19+
),
20+
((&["b", "bb", "bbb"], &["a", "aa", "aaa"]), 0),
21+
((&["a", "ab"], &["a", "a", "a", "ab"]), 1),
22+
];
23+
24+
for ((words1, words2), expected) in test_cases {
25+
assert_eq!(
26+
S::count_words(
27+
words1.iter().copied().map(str::to_string).collect(),
28+
words2.iter().copied().map(str::to_string).collect()
29+
),
30+
expected,
31+
);
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)