Keshawn_lu's Blog

Leetcode 811. 子域名访问计数

字数统计: 639阅读时长: 3 min
2022/10/05 Share

题目简介:

网站域名 "discuss.leetcode.com" 由多个子域名组成。顶级域名为 "com" ,二级域名为 "leetcode.com" ,最低一级为"discuss.leetcode.com" 。当访问域名 "discuss.leetcode.com" 时,同时也会隐式访问其父域名 "leetcode.com"以及 "com"

计数配对域名 是遵循 "rep d1.d2.d3""rep d1.d2" 格式的一个域名表示,其中 rep 表示访问域名的次数,d1.d2.d3 为域名本身。

  • 例如,"9001 discuss.leetcode.com" 就是一个 计数配对域名 ,表示 discuss.leetcode.com 被访问了 9001 次。

给你一个 计数配对域名 组成的数组 cpdomains ,解析得到输入中每个子域名对应的 计数配对域名 ,并以数组形式返回。可以按 任意顺序 返回答案。

示例 1:

1
2
3
4
输入:cpdomains = ["9001 discuss.leetcode.com"]
输出:["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]
解释:例子中仅包含一个网站域名:"discuss.leetcode.com"。
按照前文描述,子域名 "leetcode.com" 和 "com" 都会被访问,所以它们都被访问了 9001 次。

示例 2:

1
2
3
4
输入:cpdomains = ["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 次。

提示:

  • 1 <= cpdomain.length <= 100
  • 1 <= cpdomain[i].length <= 100
  • cpdomain[i] 会遵循 "rep_i d1i.d2i.d3i""rep_i d1i.d2i" 格式
  • rep_i 是范围 [1, 10^4] 内的一个整数
  • d1_id2_id3_i 由小写英文字母组成

思路:

利用哈希表存储每个网址被访问的次数即可。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public:

unordered_map<string, int> count;

void solve(string& str){

int blank = str.find(" ");
int num = stoi(str.substr(0, blank));

string web = str.substr(blank + 1, str.size() - blank);
count[web] += num;

int idx = blank + 1;
int dot = str.find(".", idx);

while(dot != string::npos){

web = str.substr(dot + 1, str.size() - dot);
count[web] += num;

dot = str.find(".", dot + 1);
}
}

vector<string> subdomainVisits(vector<string>& cpdomains) {

vector<string> res;

for(int i = 0; i < cpdomains.size(); i++){

solve(cpdomains[i]);
}

for(auto& it : count){

string now = to_string(it.second) + " " + it.first;
res.push_back(now);
}

return res;
}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: