|
| 1 | +use std::collections::HashSet; |
| 2 | + |
| 3 | +// 929. Unique Email Addresses, Easy |
| 4 | +// https://leetcode.com/problems/unique-email-addresses/ |
| 5 | +impl Solution { |
| 6 | + pub fn num_unique_emails(emails: Vec<String>) -> i32 { |
| 7 | + let mut set = HashSet::new(); |
| 8 | + |
| 9 | + for email in emails { |
| 10 | + let email: Vec<_> = email.split('@').collect(); |
| 11 | + let mut vhost: String = email[0].to_string().replace(".", ""); |
| 12 | + if vhost.contains("+") { |
| 13 | + vhost = vhost.split('+').next().unwrap().to_string(); |
| 14 | + } |
| 15 | + |
| 16 | + let domain: String = email[1].to_string(); |
| 17 | + |
| 18 | + set.insert(format!("{}@{}", vhost, domain)); |
| 19 | + } |
| 20 | + |
| 21 | + return set.len() as i32; |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +struct Solution {} |
| 26 | + |
| 27 | +#[cfg(test)] |
| 28 | +mod tests { |
| 29 | + use super::*; |
| 30 | + use crate::vec_string; |
| 31 | + |
| 32 | + #[test] |
| 33 | + fn test_num_unique_emails() { |
| 34 | + assert_eq!( |
| 35 | + Solution::num_unique_emails(vec_string![ |
| 36 | + "test.email+alex@leetcode.com", |
| 37 | + "test.e.mail+bob.cathy@leetcode.com", |
| 38 | + "testemail+david@lee.tcode.com" |
| 39 | + ]), |
| 40 | + 2 |
| 41 | + ); |
| 42 | + } |
| 43 | + |
| 44 | + #[test] |
| 45 | + fn test_num_unique_emails2() { |
| 46 | + assert_eq!(Solution::num_unique_emails(vec_string!["a@leetcode.com", "b@leetcode.com", "c@leetcode.com"]), 3); |
| 47 | + } |
| 48 | + |
| 49 | + #[test] |
| 50 | + fn test_num_unique_emails3() { |
| 51 | + assert_eq!(Solution::num_unique_emails(vec_string!["a@leetcode.com", "a@leetcode.com"]), 1); |
| 52 | + } |
| 53 | + |
| 54 | + #[test] |
| 55 | + fn test_num_unique_emails4() { |
| 56 | + assert_eq!(Solution::num_unique_emails(vec_string![]), 0); |
| 57 | + } |
| 58 | +} |
0 commit comments