diff --git a/src/lib.rs b/src/lib.rs index d866391b..8e4bb129 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1424,6 +1424,7 @@ pub mod problem_2063_vowels_of_all_substrings; pub mod problem_2068_check_whether_two_strings_are_almost_equivalent; pub mod problem_2069_walking_robot_simulation_ii; pub mod problem_2070_most_beautiful_item_for_each_query; +pub mod problem_2085_count_common_words_with_one_occurrence; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2085_count_common_words_with_one_occurrence/hash_map.rs b/src/problem_2085_count_common_words_with_one_occurrence/hash_map.rs new file mode 100644 index 00000000..4dd03071 --- /dev/null +++ b/src/problem_2085_count_common_words_with_one_occurrence/hash_map.rs @@ -0,0 +1,53 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +use std::collections::hash_map::Entry; +use std::collections::HashMap; + +impl Solution { + pub fn count_words(words1: Vec, words2: Vec) -> i32 { + let mut states = HashMap::<_, u8>::new(); + + for word in words1 { + states.entry(word).and_modify(|c| *c = 1).or_insert(0); + } + + let mut result = 0; + + for word in words2 { + if let Entry::Occupied(mut entry) = states.entry(word) { + let state = entry.get_mut(); + + if *state == 0 { + result += 1; + *state = 2; + } else { + if *state == 2 { + result -= 1; + } + + entry.remove(); + } + } + } + + result + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn count_words(words1: Vec, words2: Vec) -> i32 { + Self::count_words(words1, words2) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2085_count_common_words_with_one_occurrence/mod.rs b/src/problem_2085_count_common_words_with_one_occurrence/mod.rs new file mode 100644 index 00000000..1a2c20b9 --- /dev/null +++ b/src/problem_2085_count_common_words_with_one_occurrence/mod.rs @@ -0,0 +1,34 @@ +pub mod hash_map; + +pub trait Solution { + fn count_words(words1: Vec, words2: Vec) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + ( + ( + &["leetcode", "is", "amazing", "as", "is"] as &[_], + &["amazing", "leetcode", "is"] as &[_], + ), + 2, + ), + ((&["b", "bb", "bbb"], &["a", "aa", "aaa"]), 0), + ((&["a", "ab"], &["a", "a", "a", "ab"]), 1), + ]; + + for ((words1, words2), expected) in test_cases { + assert_eq!( + S::count_words( + words1.iter().copied().map(str::to_string).collect(), + words2.iter().copied().map(str::to_string).collect() + ), + expected, + ); + } + } +}