LeetCode 题解工作台
独特的电子邮件地址
每个 有效电子邮件地址 都由一个 本地名 和一个 域名 组成,以 '@' 符号分隔。除小写字母之外,电子邮件地址还可以含有一个或多个 '.' 或 '+' 。 例如,在 alice@leetcode.com 中, alice 是 本地名 ,而 leetcode.com 是 域名 。 如果在电子邮件地址…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以用一个哈希表 来存储所有的电子邮件地址,然后遍历数组 ,对于每个电子邮件地址,我们将其分为本地名和域名两部分,然后对本地名进行处理,去掉所有的点号和加号后面的字符,最后将处理后的本地名和域名拼接起来,加入哈希表 中。 最后返回哈希表 的大小即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
每个 有效电子邮件地址 都由一个 本地名 和一个 域名 组成,以 '@' 符号分隔。除小写字母之外,电子邮件地址还可以含有一个或多个 '.' 或 '+' 。
- 例如,在
alice@leetcode.com中,alice是 本地名 ,而leetcode.com是 域名 。
如果在电子邮件地址的 本地名 部分中的某些字符之间添加句点('.'),则发往那里的邮件将会转发到本地名中没有点的同一地址。请注意,此规则 不适用于域名 。
- 例如,
"alice.z@leetcode.com”和“alicez@leetcode.com”会转发到同一电子邮件地址。
如果在 本地名 中添加加号('+'),则会忽略第一个加号后面的所有内容。这允许过滤某些电子邮件。同样,此规则 不适用于域名 。
- 例如
m.y+name@email.com将转发到my@email.com。
可以同时使用这两个规则。
给你一个字符串数组 emails,我们会向每个 emails[i] 发送一封电子邮件。返回实际收到邮件的不同地址数目。
示例 1:
输入: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"。
示例 2:
输入:emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"] 输出:3
提示:
1 <= emails.length <= 1001 <= emails[i].length <= 100emails[i]由小写英文字母、'+'、'.'和'@'组成- 每个
emails[i]都包含有且仅有一个'@'字符 - 所有本地名和域名都不为空
- 本地名不会以
'+'字符作为开头 - 域名以
".com"后缀结尾。 - 域名在
".com"后缀前至少包含一个字符
解题思路
方法一:哈希表
我们可以用一个哈希表 来存储所有的电子邮件地址,然后遍历数组 ,对于每个电子邮件地址,我们将其分为本地名和域名两部分,然后对本地名进行处理,去掉所有的点号和加号后面的字符,最后将处理后的本地名和域名拼接起来,加入哈希表 中。
最后返回哈希表 的大小即可。
时间复杂度 ,空间复杂度 ,其中 为所有电子邮件地址的长度之和。
class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
s = set()
for email in emails:
local, domain = email.split("@")
t = []
for c in local:
if c == ".":
continue
if c == "+":
break
t.append(c)
s.add("".join(t) + "@" + domain)
return len(s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N * L) where N is the number of emails and L is the average length, due to scanning and normalizing each email. Space complexity is O(N * L) to store normalized emails in a hash set. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for O(N) array scanning with string manipulation.
- question_mark
Expect correct handling of '+' and '.' in local names.
- question_mark
Check if duplicates are correctly ignored using a hash set.
常见陷阱
外企场景- error
Forgetting to ignore characters after '+' in the local name.
- error
Removing dots from domain names instead of only the local part.
- error
Recomputing strings inefficiently leading to unnecessary time or memory use.
进阶变体
外企场景- arrow_right_alt
Return the list of normalized emails instead of just counting.
- arrow_right_alt
Handle uppercase letters by converting all to lowercase before normalization.
- arrow_right_alt
Allow arbitrary domain suffixes, not just '.com', while applying the same local name rules.