一个网站域名,如”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 次。

题解

这道题主要针对于一个 discuss.leetcode.com 域名如何拆解成 discuss.leetcode.com leetcode.com com 三个不同域名

这里可以从后往前遍历,再组合遍历过程中的字符串,单遇到 “.” 收集字符串,最终遍历到首位,再收集整个字符串就可以得到3个域名

  1. /**
  2. * @param {string[]} cpdomains
  3. * @return {string[]}
  4. */
  5. var subdomainVisits = function(cpdomains) {
  6. const map = {}
  7. for (let i = 0; i < cpdomains.length; i++) {
  8. const [num, u] = cpdomains[i].split(' ')
  9. let str = ''
  10. for (let j = u.length - 1; j >= 0; j--) {
  11. if (u[j] === '.') {
  12. if (!map[str]) {
  13. map[str] = 0
  14. }
  15. map[str] += Number(num)
  16. }
  17. str = u[j] + str
  18. if (j === 0) {
  19. if (!map[str]) {
  20. map[str] = 0
  21. }
  22. map[str] += Number(num)
  23. }
  24. }
  25. }
  26. const res = []
  27. Object.keys(map).forEach(key => {
  28. res.push(`${map[key]} ${key}`)
  29. })
  30. return res
  31. };

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subdomain-visit-count
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。