class Solution {
public:
    void SplitString(const string& s, vector<string>& v, const string& c)
    {
        string::size_type pos1, pos2;
        pos2 = s.find(c);
        pos1 = 0;
        while (string::npos != pos2)
        {
            v.push_back(s.substr(pos1, pos2 - pos1));

            pos1 = pos2 + c.size();
            pos2 = s.find(c, pos1);
        }
        if (pos1 != s.length())
            v.push_back(s.substr(pos1));
    }
    vector<string> subdomainVisits(vector<string>& cpdomains) {
        vector<string> X;
        map<string, int> MAP;
        for (auto cpdomain : cpdomains)
        {
            vector<string> v1;
            SplitString(cpdomain, v1, " ");//将访问数字和域名分开
            int count = atoi(v1[0].c_str());
            string domain = v1[1];

            vector<string> v2;
            SplitString(domain, v2, ".");
            string last = "";
            for (int i = v2.size() - 1; i >= 0; i--)
            {
                if (last == "")
                {
                    last = v2[i];
                }
                else
                {
                    last = v2[i] + "." + last;
                }
                if (MAP.find(last) != MAP.end())//找到了此项目
                {
                    MAP[last] += count;
                }
                else//未有此项
                {
                    MAP.insert(make_pair(last, count));
                }
            }
        }
        for (auto m : MAP)
        {
            string x = m.first;
            stringstream ss;
            ss << m.second;
            string ct = ss.str();
            X.push_back(ct + " " + x);
        }
        return X;
    }
};

 

posted on 2018-09-27 22:40  Sempron2800+  阅读(109)  评论(0编辑  收藏  举报