leetcode 49. Group Anagrams 哈希

Medium

3641

187

Add to List

Share
Given an array of strings, group anagrams together.

Example:

Input: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Output:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
Note:

All inputs will be in lowercase.
The order of your output does not matter.

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        int n=strs.size();
        unordered_map<string, vector<string>> mp;
        for(int i=0;i<n;i++){
            string t=strs[i];
            sort(t.begin(), t.end());
            mp[t].push_back(strs[i]);
        }
        for(auto &s:mp)
            res.push_back(s.second);
        return res;
    }
};
posted @ 2020-07-26 10:39  winechord  阅读(57)  评论(0编辑  收藏  举报