929. Unique Email Address

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.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值