[Swift]LeetCode929. 獨特的電子郵件地址 | Unique Email Addresses

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-sdfhworz-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

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

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.)app

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.)dom

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

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

Example 1:spa

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:code

  • 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。 (一樣,此規則不適用於域名。)

能夠同時使用這兩個規則。

給定電子郵件列表 emails,咱們會向列表中的每一個地址發送一封電子郵件。實際收到郵件的不一樣地址有多少?

示例:

輸入:["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
輸出:2
解釋:實際收到郵件的是 "testemail@leetcode.com" 和 "testemail@lee.tcode.com"。

提示:

  • 1 <= emails[i].length <= 100
  • 1 <= emails.length <= 100
  • 每封 emails[i] 都包含有且僅有一個 '@' 字符。

412ms

 1 class Solution {
 2     func numUniqueEmails(_ emails: [String]) -> Int {
 3         var es:Set<String> = Set<String>()
 4         for e in emails
 5         {
 6             //分割字符串
 7             var s: Array = e.components(separatedBy: "@")
 8             var str:String = String(s[0])
 9             //字符串替換
10             str = str.replacingOccurrences(of: ".", with: "")
11             //字符查找,返回字符索引
12             var ind = str.firstIndex(of: "+") ?? s[0].endIndex
13             if ind != str.endIndex
14             {
15                 //截取子字符串
16                 str = String(str[..<ind])
17             }
18             //拼接字符串,Set添加用.insert
19             es.insert(str + "@" + s[1])
20         }
21         return es.count
22     }
23 }

140ms
 1 class Solution {
 2     func numUniqueEmails(_ emails: [String]) -> Int {
 3         var dict = Dictionary<String,Set<String>>()
 4         emails.forEach { (email) in
 5             let strings = email.split(separator: "@")
 6             var address:String = String(String(strings.first!).split(separator: "+").first!)
 7             address = address.split(separator: ".").joined()
 8             let domain = String(strings[1])
 9             if dict[domain] == nil {
10                 dict[domain] = Set<String>.init([address])
11             }else{
12                 var set = dict[domain]
13                 set?.insert(address)
14                 dict[domain] = set
15             }
16         }
17         var count = 0
18         //print(dict)
19         dict.values.forEach { (set) in
20             count += set.count
21         }
22         return count
23     }
24 }

144ms

 1 class Solution {
 2     func numUniqueEmails(_ emails: [String]) -> Int {
 3         
 4         var uniqAddresses = [String]()
 5         for emails in emails {
 6             let shrinkedEmailAddress = shrinkTheEmailAddress(emails)
 7             if uniqAddresses.contains(shrinkedEmailAddress) {
 8                 continue
 9             } else {
10                 uniqAddresses.append(shrinkedEmailAddress)
11             }   
12         }
13         return uniqAddresses.count
14     }
15     
16     fileprivate func shrinkTheEmailAddress(_ address: String) -> String {
17         let chars = Array(address)
18         var plusIndex = 0
19         var atIndex = 0
20         for i in 0 ..< chars.count {
21             if chars[i] == "+" && plusIndex == 0 {
22                 plusIndex = i
23             }
24             if chars[i] == "@" {
25                 atIndex = i
26             }
27         }
28         
29         var result = ""
30         for i in 0..<plusIndex {
31             if chars[i] == "." {
32                 continue
33             }
34             result += String(chars[i])
35         }
36         for i in atIndex + 1..<chars.count {
37             result += String(chars[i])
38         }
39         return result
40     }
41 }

168ms

 1 class Solution {
 2     func numUniqueEmails(_ emails: [String]) -> Int {
 3         var set = Set<String>()
 4         for email in emails {
 5             set.insert(filter(email: email))
 6         }
 7         return set.count
 8     }
 9     
10     
11     func filter(email: String) -> String {
12         var result = ""
13         var inPrefix = true
14         var lookingForAt: Bool = false
15         for char in Array(email) {
16             let character = String(char)
17             
18             if lookingForAt && character != "@" { continue }
19             if character == "." && inPrefix { continue }
20             if character == "@" {
21                 inPrefix = false
22                 lookingForAt = false
23             }
24             
25             if character == "+" && inPrefix {
26                 lookingForAt = true
27                 continue
28             }
29             result += character
30         }
31         return result
32     }
33 }

192ms

 1 class Solution {
 2     func numUniqueEmails(_ emails: [String]) -> Int {
 3         var uniqueEmails = Set<String>()
 4 
 5         for email in emails {
 6             let emailComponents = email.split(separator: "@")
 7             let usernameComponents = emailComponents[0].split(separator: "+")
 8 
 9             var username = usernameComponents[0]
10             let domain = emailComponents[1]
11 
12             username.removeAll { $0 == "." }
13 
14             let uniqueEmail = String(username + "@" + domain)
15 
16             guard !uniqueEmails.contains(uniqueEmail) else { continue }
17             uniqueEmails.insert(uniqueEmail)
18         }
19 
20         return uniqueEmails.count
21     }
22 }

296ms

 1 class Solution {
 2     
 3     struct EmailCharacter {
 4         static let plus: Character = "+"
 5         static let atTheRate: Character = "@"
 6         static let dot: Character = "."
 7     }
 8 
 9     func numUniqueEmails(_ emails: [String]) -> Int {
10 
11         var emailAddresses = Set<String>()
12 
13         for email in emails {
14             let emailParts = email.split(separator: EmailCharacter.atTheRate)
15             if emailParts.count == 2 {
16                 let localName = String(emailParts[0])
17                 let domainName = String(emailParts[1])
18                 if let sanitizedLocalName = self.sanitizedLocalName(localName) {
19                     emailAddresses.insert(sanitizedLocalName + domainName)
20                 }
21             } else {
22                 continue
23             }
24         }
25 
26         return emailAddresses.count
27     }
28 
29     func sanitizedLocalName(_ localName: String) -> String? {
30         let localName = localName.replacingOccurrences(of: String(EmailCharacter.dot), with: "", options: NSString.CompareOptions.literal, range: nil)
31         let names = localName.split(separator: EmailCharacter.plus)
32 
33         guard names.count > 0 else {
34             return localName
35         }
36 
37         let firstSplitName = names[0]
38         if firstSplitName.hasPrefix(String(EmailCharacter.plus)) {
39             return localName
40         }
41 
42         return String(firstSplitName)
43     }
44     
45 }
相關文章
相關標籤/搜索