929. Unique Email Addresses

class Solution:
    def numUniqueEmails(self, emails: 'List[str]') -> 'int':
        accept = []
        for email in emails:
            local = email.split('@')[0]
            domain = email.split('@')[1]
            if '+' in local:
                local = local.split('+')[0]
            if '.' in local:
                local = local.replace('.','')
            result = local+domain
            if result not in accept:
                accept.append(result)
        return len(accept)

 其中:速度76ms,內存12.7Mpython

 優化一:使用set直接去重複,使用''.join()進行字符拼接app

class Solution:
    def numUniqueEmails(self, emails: 'List[str]') -> 'int':
        accept = set()
        for email in emails:
            local,domain = email.split('@')
            local = ''.join(local.split('+')[0].split('.'))
            result = local + '@' +domain
            accept.add(result)
        return len(accept)

  速度:48ms,內存12.6Mdom

優化二:使用map映射的方式,不用手動申請內存,可能map函數自動申請了內存,因此內存沒有降下來。函數

class Solution:
    def numUniqueEmails(self, emails: 'List[str]') -> 'int':
        def processone(email):
            i = email.find('@')
            j = email.find('+')
            if j < i and j>0:
                return ''.join(email[:j].split('.')) + email[i:]
            elif j == 0:
                return email[i:]
            else:
                return ''.join(email[:i].split('.')) + email[i:]
        
        return len(set(map(processone,emails)))

  速度:44ms,內存12.5M優化

相關文章
相關標籤/搜索