From 48587158b25124a81ec00af52d1db85429bf7e28 Mon Sep 17 00:00:00 2001 From: Ivan Reshetnikov Date: Wed, 7 Feb 2024 21:46:21 +0500 Subject: [PATCH] chore: optimize rust program, add tests --- .../0929-unique-email-addresses/src/lib.rs | 57 +++++++++++++++++++ .../0929-unique-email-addresses/src/main.rs | 29 ---------- 2 files changed, 57 insertions(+), 29 deletions(-) create mode 100644 leetcode/0929-unique-email-addresses/src/lib.rs delete mode 100644 leetcode/0929-unique-email-addresses/src/main.rs diff --git a/leetcode/0929-unique-email-addresses/src/lib.rs b/leetcode/0929-unique-email-addresses/src/lib.rs new file mode 100644 index 0000000..7d5d18e --- /dev/null +++ b/leetcode/0929-unique-email-addresses/src/lib.rs @@ -0,0 +1,57 @@ +use std::collections::HashSet; + +fn process_local_part(s: &str) -> String { + match s.find('+') { + Some(plus_index) => &s[0..plus_index], + None => s, + } + .replace('.', "") +} + +#[cfg(test)] +mod process_local_part_tests { + use super::process_local_part; + + #[test] + fn processing_works() { + let result = process_local_part("a.b+c"); + assert_eq!(result, "ab"); + } + + #[test] + fn processing_without_plus_works() { + let result = process_local_part("a.b"); + assert_eq!(result, "ab"); + } +} + +pub fn num_unique_emails(emails: Vec) -> i32 { + let mut unique_emails = HashSet::new(); + + for email in emails.iter() { + let parts: Vec<&str> = email.split('@').collect(); + unique_emails.insert(format!("{}@{}", process_local_part(parts[0]), parts[1])); + } + + unique_emails.len() as i32 +} + +#[cfg(test)] +mod num_unique_emails_tests { + use super::num_unique_emails; + + #[test] + fn num_unique_emails_is_correct() { + let result = num_unique_emails( + [ + "test.email+alex@leetcode.com", + "test.e.mail+bob.cathy@leetcode.com", + "testemail+david@lee.tcode.com", + ] + .iter() + .map(|s| s.to_string()) + .collect(), + ); + assert_eq!(result, 2) + } +} diff --git a/leetcode/0929-unique-email-addresses/src/main.rs b/leetcode/0929-unique-email-addresses/src/main.rs deleted file mode 100644 index fd212a0..0000000 --- a/leetcode/0929-unique-email-addresses/src/main.rs +++ /dev/null @@ -1,29 +0,0 @@ -use std::collections::HashSet; - -pub fn num_unique_emails(emails: Vec) -> i32 { - let mut unique_emails = HashSet::new(); - - for email in emails.iter() { - let mut parts: Vec = email - .split("@") - .map(|s| s.to_string()) - .collect(); - parts[0] = parts[0] - .replace(".", "") - .split("+") - .collect::>()[0] - .to_string(); - unique_emails.insert(format!("{}@{}", parts[0], parts[1])); - } - - unique_emails.len() as i32 -} - -fn main() { - let inp: Vec = vec![ - "test.email+alex@leetcode.com", - "test.e.mail+bob.cathy@leetcode.com", - "testemail+david@lee.tcode.com", - ].iter().map(|s| s.to_string()).collect(); - println!("{}", num_unique_emails(inp)); -}