[leetcode]Group Anagrams

链接:https://leetcode.com/problems/group-anagrams/description/

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) {
        unordered_map<string,multiset<string>> mp;
        for(string s:strs)
        {
            string t=s;
            sort(t.begin(),t.end());
            mp[t].insert(s);
        }
        vector<vector<string>> anagrams;
        for(auto m:mp)
        {
            vector<string> anagram(m.second.begin(),m.second.end());
            anagrams.push_back(anagram);
        }
        return anagrams;
    }
};

猜你喜欢

转载自blog.csdn.net/xiaocong1990/article/details/82287463