49. Group Anagrams

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> groupAnagrams(vector& strs) {
        vector> res;
        unordered_map> strMap;
        for(auto str : strs){
            string temp = str;
            sort(temp.begin(), temp.end());
            strMap[temp].push_back(str);
        }
        for(auto group : strMap){
            res.push_back(group.second);
        }
        return res;
    }
};

你可能感兴趣的:(49. Group Anagrams)