问题描述
一个网站域名,如"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 次。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subdomain-visit-count
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行结果
代码描述
思路:
- 对域名字符串进行分割。以空格为界,分割成数字部分; 以点为界,分割要求的域名部分。
- 对分割好的域名部分,作为键,存入map;
- 对数字部分 string 转成 int ,作为值,对应键存入map;
- 将map生成之后,进行输出到vector。输出的同时,把值 int 转成string。
class Solution {
public:
vector<string> subdomainVisits(vector<string>& cpdomains) {
map<string, int> str_cnt;
vector<string> vec;
for(int i = 0; i < cpdomains.size(); ++i)
{
int space = cpdomains[i].find(' ')+1; // 查找空格的位置,返回空格的下一个索引值
int j = 0;
string num;
int val;
while(j < (space - 1)) // 取数字
{
num += cpdomains[i][j];
++j;
}
val = sToInt(num); // 把string转成int
int pt1 = cpdomains[i].find('.')+1; // 查找第一个 . 的位置
int pt2 = cpdomains[i].rfind('.')+1; // 查找最后一个 . 的位置
if(pt1 == pt2) // 如果只有一个 .
{
str_cnt[cpdomains[i].substr(pt2)] += val;
str_cnt[cpdomains[i].substr(space)] += val;
}
else // 有两个 .
{
str_cnt[cpdomains[i].substr(pt1)] += val;
str_cnt[cpdomains[i].substr(pt2)] += val;
str_cnt[cpdomains[i].substr(space)] += val;
}
}
vec = map_vec(str_cnt); // 把map转成vector
return vec;
}
// string 转 int
int sToInt(string s)
{
int res = 0;
int k = 1;
for(int i = s.size() - 1; i >= 0; --i)
{
res += int(s[i] - 48)*k;
k*=10;
}
return res;
}
// map转vector
vector<string> map_vec(map<string, int> s_i)
{
vector<string> res;
map<string, int>::iterator it = s_i.begin();
for(; it != s_i.end(); ++it)
{
string temp = to_String(it->second);
temp += " ";
temp += it->first;
res.push_back(temp);
}
return res;
}
// int转string
string to_String(int val)
{
string res;
while(val > 0)
{
res += char(val%10 + '0');
val /= 10;
}
reverse(res.begin(), res.end()); // 一定要记得反转
return res;
}
};