子域名访问计数(leetcode 811)

题目:

输入:[“900 google.mail.com”, “50 yahoo.com”, “1 intel.mail.com”, “5wiki.org”]
输出:[“901 mail.com”,“50 yahoo.com”,“900google.mail.com”,“5wiki.org”,“5 org”,“1 intel.mail.com”,“951 com”]
说明:按照假设,会访问"google.mail.com" 900次,“yahoo.com"50次,“intel.mail.com” 1次,“wiki.org” 5次。
而对于父域名,会访问"mail.com” 900+1 =901次,“com” 900 + 50 + 1 = 951次,和 “org” 5 次。*

分析

  • 1.遍历将数组的每个元素以空格为依据进行第一次分割:

    • public String[] split(String regex):按照参数的规则,将字符串切割为若干个
  • 2.遍历第一次分割好的字符串数组:

    • 0下标处是次数(字符串类型)—需要转化为int型:
      int n=Integer.valueOf(a[0]);
    • 1下标处是字符串 :
      • 需要再次以 . 为标志进行切割
    • 遍历第二次切割好的字符串数组,进行按题目要求进行合并
      • 已合并的字符串作为key,次数n作为value向Map集合做添加运算
  • 3.遍历Map集合,得到键值对

    • getKey()得到键,getValue()得到值
    • 拼接值与键,将的得到的新字符串添加到List集合中
    • 返回List集合
  • 4.调用函数,打印List集合

ublic class Demo06Practise03 {
    public static List<String> subdomainVisits(String[] cpdomains){
        Map<String,Integer>map=new HashMap<>();
        for (String cpdomain : cpdomains) {
            String[]a=cpdomain.split(" ");
            int n=Integer.valueOf(a[0]);
            String []domain=a[1].split("\\.");
            for(int i=0;i<domain.length;i++){
                String[]b= Arrays.copyOfRange(domain,i,domain.length);
                String result=String.join(".",b);
                int oldCount=map.getOrDefault(result,0);
                map.put(result,oldCount+n);
            }
        }
        List<String> list=new LinkedList<>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String result=entry.getKey();
            int count=entry.getValue();
            String s=count+" "+result;
            list.add(s);
        }
        return list;
    }

    public static void main(String[] args) {
        String[]str1={"9001 discuss.leetcode.com"};
        List<String> result1=subdomainVisits(str1);
        System.out.println(result1);
        String[]str2={"900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"};
        List<String>result2=subdomainVisits(str2);
        System.out.println(result2);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值