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 }