leetcode题解之分解字符串域名

本文介绍了一种统计网站子域名访问次数的方法。通过解析输入的域名字符串,利用unordered_map进行计数,最终输出各子域及顶级域的访问次数。

1、题目描述

A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com", and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.

Now, call a "count-paired domain" to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be "9001 discuss.leetcode.com".

We are given a list cpdomains of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.

原题: https://leetcode.com/problems/subdomain-visit-count/description/

题目的意思是输入一个字符串向量,每个字符串代表一个域名和访问这个域名的次数,统计将域名拆分之后。所有的的域名的访问次数。

 

2、题目分析

由于输入的每个字符串都是string,因此应该考虑先将字符串拆分,然后使用一个unorder_map<string,int>统计每个子域名出现的次数。

 

3、代码

 1 vector<string> subdomainVisits(vector<string>& cpdomains) {
 2         // 思路可以将字符串先分割,然后使用 unorder_set 计数
 3         // 使用一个子函数将每个cpdomains 分割
 4         
 5         unordered_map<string,int> m;
 6         
 7         
 8         for(auto Itr = cpdomains.begin() ; Itr != cpdomains.end(); Itr++ )
 9         {
10             vector<string> Sproc = split_cpdomains(*Itr);
11             for(auto itr = Sproc.begin() + 1; itr != Sproc.end(); itr++ )
12             {
13                 m[*itr] += stoi(Sproc[0]);
14             }
15         }
16         
17         vector<string> ans;
18         for(auto it = m.begin() ; it != m.end(); it++ )
19         {
20             ans.push_back( to_string(it->second) +" "+ it->first );
21         }
22         
23         return ans;
24         
25         
26     }
27     
28     vector<string> split_cpdomains(string & s)
29     {
30         vector<string> res;
31         
32         int i = 0;
33         for(auto itr = s.begin() ; itr != s.end() ; itr++)   // 以下代码可以用 string 的find() 成员函数简化
34         {
35             i++;
36             if( *itr == ' ')
37             {
38                 res.push_back( s.substr(0,i )); // put number in
39                 break;
40             }
41         }
42         
43         
44         res.push_back( s.substr( s.find_first_of(' ') + 1 )) ;
45         res.push_back(  s.substr(s.find_first_of(".") +1 )); 
46         if( s.find_first_of(".") != s.find_last_of(".") )
47             res.push_back( s.substr( s.find_last_of(".") + 1) ) ;
48                      
49             
50         return res;
51     }

 

转载于:https://www.cnblogs.com/wangxiaoyong/p/8710886.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值