| 每日一题做题记录,参考官方和三叶的题解 |
题目要求
思路:模拟模拟
- 根据不同符号判定当前字符走向;
- 用哈希表记录合法地址。
- Java和C++遇到域名直接跳出循环,把后面的域名直接加入结果,Rust子串这个格式不太熟悉,就多搞了个标记,域名也套在循环里加入结果。
Java
class Solution {
public int numUniqueEmails(String[] emails) {
Set<String> set = new HashSet<>();
for(String e : emails) {
StringBuilder sb = new StringBuilder();
int n = e.length(), i = 0;
boolean ok = true;
while(i < n) {
char c = e.charAt(i);
if(c == '@') // 退出循环
break;
if(c == '.' && ++i >= 0) // 忽略,直接下一位
continue;
if(c == '+') // 后面的无效
ok = false;
if(ok)
sb.append(c);
i++;
}
set.add(sb.append(e.substring(i)).toString()); // 域名补上,加入结果
}
return set.size();
}
}
- 时间复杂度:
- 空间复杂度:
C++
class Solution {
public:
int numUniqueEmails(vector<string>& emails) {
unordered_set<string> set;
for(auto e : emails) {
string sb = "";
int n = e.size(), i = 0;
bool ok = true;
while(i < n) {
char c = e[i];
if(c == '@') // 退出循环
break;
if(c == '.' && ++i >= 0) // 忽略,直接下一位
continue;
if(c == '+') // 后面的无效
ok = false;
if(ok)
sb += c;
i++;
}
set.emplace(sb += e.substr(i)); // 域名补上,加入结果
}
return set.size();
}
};
- 时间复杂度:
- 空间复杂度:
Rust
use std::collections::HashSet;
impl Solution {
pub fn num_unique_emails(emails: Vec<String>) -> i32 {
let mut set = HashSet::new();
for e in &emails {
let mut sb = String::new();
let mut domain = false;
let mut ok = true;
for c in e.chars() {
if domain { // 域名直接补上
sb.push(c);
}
else {
if c == '@' { // 后面是域名
sb.push(c);
domain = true;
continue;
}
if c == '.' { // 忽略直接下一位
continue;
}
if c == '+' { // 后面的无效
ok = false;
}
if ok {
sb.push(c);
}
}
}
set.insert(sb); // 加入结果
}
set.len() as i32
}
}
- 时间复杂度:
- 空间复杂度:
总结
模拟模拟~
假期里的简单题就很快乐!
| 欢迎指正与讨论! |