前往
大廳
主題

C/C++紀錄三十四 leetcode. <811. Subdomain Visit Count> 2019/2/12

艾倫D索妮雅 | 2021-06-09 19:57:05 | 巴幣 0 | 人氣 122

class Solution
{
    public:
        vector<string> subdomainVisits(vector<string>& cpdomains)
        {
            unordered_map<string, int> c;
            for (auto cd : cpdomains)
            {
                int i = cd.find(" ");//利用string的find()函式,找到空格的位子
                int n = stoi(cd.substr (0, i));//std::stoi stoi函式可以將str中的數字轉成int
                string s = cd.substr (i + 1, cd.size () - i - 1);//substr可以將字串拆開來讀取,這裡是讀取拆到空格" "後的字串
                for (int i = 0; i < s.size(); ++i) if (s[i] == '.') c[s.substr(i + 1, s.size () - i)] += n;
                c[s] += n;
            }
            vector<string> res;
            for (auto k : c) res.push_back (to_string(k.second) + " " + k.first);
            return res;
        }
};

創作回應

更多創作