面试题 10.02. 变位词组

面试题 10.02. 变位词组
编写一种方法,对字符串数组进行排序,将所有变位词组合在一起。变位词是指字母相同,但排列不同的字符串。

注意:本题相对原题稍作修改

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        unordered_map<string, vector<string>> ump;
        for(int i = 0; i < strs.size(); ++i){
            string key = strs[i];
            sort(key.begin(), key.end());
            ump[key].emplace_back(strs[i]);
        }
        for(auto it = ump.begin(); it != ump.end(); ++it){
            res.push_back(it->second);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43599304/article/details/121117791