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.7M
优化一:使用set直接去重复,使用''.join()进行字符拼接
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.6M
优化二:使用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