929. Unique Email Addresses

Link: https://leetcode.com/problems/unique-email-addresses/

Every email consists of a local name and a domain name, separated by the @ sign.

For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.

Besides lowercase letters, these emails may contain ‘.’s or ‘+’s.

If you add periods (‘.’) between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, “alice.z@leetcode.com“ and “alicez@leetcode.com“ forward to the same email address. (Note that this rule does not apply for domain names.)

If you add a plus (‘+’) in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.)

It is possible to use both of these rules at the same time.

Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails?

Example 1:

Input: ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
Output: 2
Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails

Note:

  • 1 <= emails[i].length <= 100
  • 1 <= emails.length <= 100
  • Each emails[i] contains exactly one ‘@’ character.

題目翻譯:

每封電子郵件都包含本地名稱和域名,以@符號分隔。

例如,在 alice@leetcode.com 中,alice 是本地名稱,leetcode.com 是域名。

除了小寫字母,這些電子郵件可能包含’。’或’+’。

如果在電子郵件地址的本地名稱部分中的某些字符之間添加句點(’.’),則在那裡發送的郵件將被轉發到本地名稱中沒有點的同一地址。例如,“alice.z@leetcode.com”和“alicez@leetcode.com”轉發到同一個電子郵件地址。 (請注意,此規則不適用於域名。)

如果在本地名稱中添加加號(’+’),則會忽略第一個加號後面的所有內容。這允許過濾某些電子郵件,例如 m.y+name
email.com 將轉發到 my@email.com。 (同樣,此規則不適用於域名。)

可以同時使用這兩個規則。

鑑於電子郵件列表,我們會向列表中的每個地址發送一封電子郵件。有多少不同的地址實際接收郵件?

程式思路:

準備一個 set 的容器,每條 email 處理時,在遇到‘@’or’+’ 符號前,先判斷 account 的 id 並忽略’.’遇到’+’開始忽略直到遇到‘@’,一遇到‘@’ 直接複製至後段。

class Solution {
public:
    int numUniqueEmails(vector<string>& emails) {
        set<string> email_set;
        for(auto email : emails) {
            string tmp;
            bool ignore = false;
            for(int i = 0; i < email.length(); i++) {
                if(email[i] == '@') {
                   tmp+=email.substr(i,email.length()-i);
                   break;
                }
                else if(email[i] == '+') {
                    ignore = true;
                }else if( !ignore  && email[i] != '.')
                {
                    tmp += email[i];
                }
            }
            email_set.insert(tmp);
        }
        return email_set.size();
    }
};

  目錄