文章目录
问题描述
Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods (’.’) between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.)
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?
理解
这个问题很简单(自己还想了很久=。=),将邮件地址local name中包含的点(非首位)去掉,以及去掉local name中’+'和它以后的所有字符。
代码
class Solution {
public int numUniqueEmails(String[] emails) {
Map<String, Integer> emailMap = new HashMap<String, Integer>();
char DOT = '.';
char PLUS = '+';
int diffAddress = 0;
for(String email : emails){
//获取local name
String localName = email.substring(0,email.indexOf('@'));
StringBuffer tempBuffer = new StringBuffer();
for(int i = 1;i < localName.length();i++){
//去掉加号之后的字符
if(localName.charAt(i) == PLUS)
break;
if(localName.charAt(i) != PLUS && localName.charAt(i) != DOT){
tempBuffer.append(String.valueOf(localName.charAt(i)));
}
}
String uniLocalName = tempBuffer.toString();
if(!emailMap.keySet().contains(uniLocalName)){
System.out.println(uniLocalName + email.substring(email.indexOf('@')));
emailMap.put(uniLocalName + email.substring(email.indexOf('@')), 1);
}
}
for(String key:emailMap.keySet()){
diffAddress++;
}
return diffAddress;
}
}
改进
看了答案发现想复杂了好多…第一是最近一看到题就想用哈希表,set也没怎么用过。还有String里面好多操作都没怎么看…
String.replaceAll(char, char) String.contains() 都没见过!!菜!!
代(da)码(an)
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();
}
}