Group Anagrams

题目:

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

    1. For the return value, each inner list's elements must follow the lexicographic order.
    2. All inputs will be in lower-case.

cpp:

class Solution {
    public:
       vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> result;
        unordered_map<string,multiset<string>> dict;
        for(auto str : strs){
            string s = str;
            sort(s.begin(),s.end());
            dict[s].insert(str);
        }
        for(auto a : dict){
            vector<string> temp(a.second.begin(),a.second.end());
            result.push_back(temp);
        }
        return result;
    }
};

python:

class Solution(object):
    def groupAnagrams(self,strs):
        res = collections.defaultdict(list)
        for s in strs:
            res["".join(sorted(s))].append(s)
        return map(lambda k:sorted(res[k]),res.keys())

 

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