LeetCode 49. 字母异位词分组

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:

所有输入均为小写字母。
不考虑答案输出的顺序。

算法:直接哈希

class Solution {
public:
    unordered_map<string, vector<string>>h;
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>>res;
        for(auto &x:strs){
            string cur=x;
            sort(cur.begin(),cur.end());
            h[cur].push_back(x);
        }
        for(auto it=h.begin();it!=h.end();++it)
            res.push_back(it->second);
        return res;
    }
};

 

posted @ 2019-07-28 22:52  YF-1994  阅读(99)  评论(0编辑  收藏  举报