[leetcode]811. Subdomain Visit Count
Analysis
old friends~—— [嘻嘻~]
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.
题目很简单,只是做起来比较麻烦,用到了string的分割,可以看一下这篇博客:https://www.jianshu.com/p/5876a9f49413,然后用一个hash table记录一下就行了~
Implement
class Solution {
public:
vector<string> subdomainVisits(vector<string>& cpdomains) {
map<string, int> mymap;
int time;
int pos;
int len;
int len1;
string tmp;
string domain;
for(int i=0; i<cpdomains.size(); i++){
domain = cpdomains[i];
domain += ".";
len = domain.length();
pos = domain.find(" ");
tmp = domain.substr(0, pos);
time = stoi(tmp);
domain = domain.substr(pos+1, len);
pos = domain.find(".");
while(pos != domain.npos){
len1 = domain.length();
if(domain[len1-1] == '.')
tmp = domain.substr(0, domain.length()-1);
else
tmp = domain;
if(mymap.find(tmp) != mymap.end())
mymap[tmp] += time;
else
mymap[tmp] = time;
domain = domain.substr(pos+1, domain.length());
pos = domain.find(".");
}
}
vector<string> res;
map<string, int>::iterator it;
for(it=mymap.begin(); it!=mymap.end(); it++){
tmp = "";
tmp += to_string(it->second);
tmp += " ";
tmp += it->first;
res.push_back(tmp);
}
return res;
}
};