可以锻炼使用java String的split()、replacAll()等方法和正则表达式的题
思路很简单,但实现时有坑:
用'.'字符分割字符串,不能用s.split("."),因为'.'是特殊字符,而split()是用正则表达式匹配参数
这里需要用"\\."或"[.]"作为参数
split()特殊字符的坑:
/**
* Runtime: 7 ms, faster than 87.20%
* Memory Usage: 39.3 MB, less than 62.20%
*/
class Solution {
public int numUniqueEmails(String[] emails) {
Set<String> set = new HashSet(); // use set to avoid duplicate processed emails
for (String email : emails) {
// devide each email to a local name and a domain name
String[] names = email.split("@");
// ignore the substring of the local name after '+'
int idx = names[0].indexOf('+');
if (idx >= 0) {
names[0] = names[0].substring(0, idx);
}
String[] segs = names[0].split("\\."); // '.' is special character and cannot be directly used to split String, use "\\." or "[.]" instead
StringBuilder sb = new StringBuilder();
for (String seg : segs) {
sb.append(seg);
}
// recombine the processed local name with the domain name
sb.append('@');
sb.append(names[1]);
set.add(sb.toString());
}
return set.size();
}
}
/**
* 用replaceAll()方法,用空字符串替换所有".",来忽略local name里的"."
* 用split()方法将local name分成"+"前后的两个子串,只取第一个,来忽略local name里"+"后面的部分
* 注意"."和"+"都要写成正则表达式版
* 简化了代码但用了没必要的方法,效率降低
* Runtime: 25 ms, faster than 30.68%
* Memory Usage: 40.4 MB, less than 27.01%
*/
class Solution {
public int numUniqueEmails(String[] emails) {
Set<String> set = new HashSet(); // use set to avoid duplicate processed emails
for (String email : emails) {
String[] names = email.split("@");
names[0] = names[0].replaceAll("\\.", ""); // ignore '.' in the local name
StringBuilder sb = new StringBuilder();
sb.append(names[0].split("\\+")[0]); // ignore the substring after '+' in the local name
sb.append("@");
sb.append(names[1]);
set.add(sb.toString());
}
return set.size();
}
}
/**
* 相比于上一段,没有用StringBuilder,直接字符串相加
* 代码越来越精简,但效率越来越低
* Runtime: 36 ms, faster than 16.55%
* Memory Usage: 40.5 MB, less than 25.59%
*/
class Solution {
public int numUniqueEmails(String[] emails) {
Set<String> set = new HashSet(); // use set to avoid duplicate processed emails
for (String email : emails) {
String[] names = email.split("@");
names[0] = names[0].replaceAll("\\.", ""); // ignore '.' in the local name
set.add(names[0].split("\\+")[0] + "@" + names[1]);
}
return set.size();
}
}