leetcode 49 字母异位词分组

 

 

需要好好研究各种写法。

C++解法

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> result;
        if (strs.size() == 0) return result;
        unordered_map<string, vector<string>> hash_map;

        for (int i = 0; i < strs.size(); i++)
        {
            string key = strs[i];
            sort(key.begin(),key.end());

            /*
            if (hash_map.count(key) == 0)
            {
                hash_map.insert({ key, vector<string>() });
            }
            */
            
            hash_map[key].push_back(strs[i]);
        }

        for (auto it = hash_map.begin(); it != hash_map.end(); it++)
        {
            vector<string>& value = it->second;
            result.push_back(value);
        }

        return result;
    }
};

 

posted @ 2024-02-14 23:14  repinkply  阅读(18)  评论(0)    收藏  举报