If you add a plus ('+'
) in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com
will be forwarded to my@email.com
. (Again, this rule does not apply for domain names.)
It is possible to use both of these rules at the same time.
Given a list of emails
, we send one email to each address in the list. How many different addresses actually receive mails?
Example 1:
Input: ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
Output: 2
Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails
本菜鸟代码:
class Solution {
public int numUniqueEmails(String[] emails) {
HashSet stringSet = new HashSet();
String s = null;
for(int i = 0;i<emails.length;i++){
s = "";
int flagplus = 0;
int flagat = 0;
for(int j = 0;j<emails[i].length();j++){
char ss = emails[i].charAt(j);
if(ss!='@'&&flagplus==0){
if(ss!='.'&&ss!='+') s+=ss;
else{
if(ss=='+') flagplus = 1;
}
}else{
if(ss=='@'||flagat==1) {
flagat = 1;
s+=ss;
}
}
}
stringSet.add(s);
}
return stringSet.size();
}
}
我的思路是:
对于‘+’ 和‘@’设置两个flag,如果遇到‘+’,就一直不添加字符,直到遇到了‘@’。在‘@’以后都直接添加字符。为了统计不重复的字符串,我用了HashSet来存储。最后返回HashSet的大小。
官方的答案是:
class Solution {
public int numUniqueEmails(String[] emails) {
Set<String> seen = new HashSet();
for (String email: emails) {
int i = email.indexOf('@');
String local = email.substring(0, i);
String rest = email.substring(i);
if (local.contains("+")) {
local = local.substring(0, local.indexOf('+'));
}
local = local.replaceAll(".", "");
seen.add(local + rest);
}
return seen.size();
}
}
官方的答案非常清楚。但是用到了很多子函数:indexOf , contains, substring,replaceAll.