LeetCode: 929. 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?


理解一下:
一個(gè) 郵件地址的數(shù)組 emails = [String]()
篩選出其中不同的郵件地址. 有幾種情況被判定為相同郵件地址.

舉例子一個(gè)郵箱地址: myEmail@qq.com
其中@前面的部分 myEmail部分. 可能包含 ('.'), ('+')的符號(hào).

('.') 的規(guī)則
alicez@leetcode.comalice.z@leetcode.com 相同.
也就是忽略 @ 符號(hào)前面部分的 . 符號(hào)

('+') 的規(guī)則
m.y+name@email.commy@email.com 相同
也就是忽略掉 + 符號(hào) 到 @ 符號(hào)之間的所有字符

如果 . 符號(hào), 在 @ 符號(hào)后面則不忽略 . 符號(hào)

例子:

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

Note:

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

我的寫法

class Solution {
    func numUniqueEmails(_ emails: [String]) -> Int {
        var email_dict = [String: Bool]()
        for (_, email) in emails.enumerated() {
            var email_key = ""
            var can_offset = true
            var before_point = true
            for (offset, element) in email.enumerated() {
                if 0 == offset, element == "+" { break }
                if element == "+" { can_offset = false }
                if element == "@" {
                    can_offset = true
                    before_point = false
                }
                if "." != element, can_offset {
                    email_key.append(element)
                }
                
                if "." == element, false == before_point {
                    email_key.append(element)
                }
            }
            if !email_key.isEmpty {
                email_dict[email_key] = true
            }
        }
        return email_dict.count
    }
}

LeetCode地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容