Rust LeetCode 練習:929 Unique Email Addresses

LeetCode 929 Unique Email Addresses優化

題目大意:郵箱地址格式爲[本地名]@[域名],其中[本地名]存在+.兩種特殊狀況。如今輸入一組郵箱地址,要求進行以下處理,而後輸出非重複的地址數量。ui

  • +,忽略其後至@前的全部字符。
  • .,忽略之。
  1. 樸素實現:(1)過濾本地名中+@以前全部字符。(2)過濾本地名中.字符。(3)將處理好的地址列表進行去重操做。(4)返回最終數量。 Runtime: 4 ms Memory Usage: 892.9 KB。spa

    pub fn num_unique_emails(emails: Vec<String>) -> i32 {
        let mut num = 0;
        let mut process_emails = vec![];
        process_emails.clone_from(&emails);
        let mut process_emails = process_emails
            .iter_mut()
            .map(|s| {
                if let Some(plus) = s.find('+') {
                    if let Some(at) = s.find('@') {
                        if at > plus {
                            s.replace_range(plus..at, "");
                        }
                    }
                }
                s
            })
            .map(|s| {
                while let Some(dot) = s.find('.') {
                    if let Some(at) = s.find('@') {
                        if dot < at {
                            s.replace_range(dot..(dot + 1), "");
                        } else {
                            break;
                        }
                    }
                }
                s
            })
            .collect::<Vec<_>>();
        process_emails.sort();
        process_emails.dedup_by(|a, b| a.eq(&b));
        process_emails.len() as i32
    }
    複製代碼
  2. 優化:利用HashSet去重。 Runtime: 4 ms Memory Usage: 921.6 KBcode

    pub fn num_unique_emails(emails: Vec<String>) -> i32 {
        use std::collections::HashSet;
        let mut unique_emails = HashSet::<String>::new();
        for email in &emails {
            let email: Vec<&str> = email.split('@').collect::<Vec<_>>();
            let mut local_name = email[0].to_owned();
            if let Some(plus) = local_name.find('+') {
                local_name.replace_range(plus..local_name.len(), "");
            };
            local_name = local_name.replace('.', "");
            unique_emails.insert(local_name + email[1]);
        }
        unique_emails.len() as i32
    }
    複製代碼
  3. 代碼簡化:利用for_each迭代器。使人困惑的是,內存暴漲到2.6 MB。 Runtime: 4 ms Memory Usage: 2.6 MB內存

    pub fn num_unique_emails(emails: Vec<String>) -> i32 {
        use std::collections::HashSet;
        let mut unique_emails = HashSet::<String>::new();
        emails.into_iter().for_each(|s| {
            let email = s.split("@").collect::<Vec<&str>>();
            let mut local_name = email[0].to_owned();
            if let Some(plus) = local_name.find('+') {
                local_name.replace_range(plus.., "");
            }
            local_name = local_name.replace('.', "");
            unique_emails.insert(local_name + email[1]);
        });
        unique_emails.len() as i32
    }
    複製代碼
相關文章
相關標籤/搜索