811. 子域名访问计数

一个网站域名,如"discuss.leetcode.com",包含了多个子域名。作为顶级域名,常用的有"com",下一级则有"leetcode.com",最低的一级为"discuss.leetcode.com"。当我们访问域名"discuss.leetcode.com"时,也同时访问了其父域名"leetcode.com"以及顶级域名 "com"。

给定一个带访问次数和域名的组合,要求分别计算每个域名被访问的次数。其格式为访问次数+空格+地址,例如:"9001 discuss.leetcode.com"。

接下来会给出一组访问次数和域名组合的列表cpdomains 。要求解析出所有域名的访问次数,输出格式和输入格式相同,不限定先后顺序。

示例 1:
输入: 
["9001 discuss.leetcode.com"]
输出: 
["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
说明: 
例子中仅包含一个网站域名:"discuss.leetcode.com"。按照前文假设,子域名"leetcode.com"和"com"都会被访问,所以它们都被访问了9001次。
示例 2
输入: 
["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
输出: 
["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.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 次。

注意事项:

  •  cpdomains 的长度小于 100
  • 每个域名的长度小于100
  • 每个域名地址包含一个或两个"."符号。
  • 输入中任意一个域名的访问次数都小于10000
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution811 {
	public List<String> subdomainVisits(String[] cpdomains) {
		HashMap<String, Integer> hm = new HashMap<String, Integer>();
		List<String> out = new ArrayList<String>();
		for (int i = 0; i < cpdomains.length; i++) {
			String[] arrtemp = cpdomains[i].split("\\s+");
			// System.out.println(arrtemp[1]);
			// System.out.println(arrtemp[0]);
			String[] domtemp = arrtemp[1].split("\\.");
			for (int j = 0; j < domtemp.length; j++) {
				String t = "";
				for (int k = j; k < domtemp.length; k++) {
					t = t + "." + domtemp[k];
				}
				t = t.substring(1, t.length());
				// System.out.println(t);
				if (hm.containsKey(t)) {
					hm.put(t, hm.get(t) + Integer.parseInt(arrtemp[0]));

				} else {
					hm.put(t, Integer.parseInt(arrtemp[0]));
				}
			}

		}

		for (Map.Entry<String, Integer> set : hm.entrySet()) {

			// Printing all elemnts of a Map
			// System.out.println(set.getKey() + " = " + set.getValue().toString());
			out.add(set.getValue().toString() + " " + set.getKey());
		}

		return out;

	}

	public static void main(String[] args) {

		Solution811 sol = new Solution811();

		String[] cpdomains = { "900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org" };

		System.out.println(sol.subdomainVisits(cpdomains));
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值