Group Anagrams - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Saturday, 8 August 2020

Group Anagrams

Group Anagrams


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<vector<string>> groupAnagrams(vector<string>& strs) {
       
       unordered_map<string,vector<string> > mp;
        for(int i=0;i<strs.size();++i)
        {
            string s=strs[i];
            sort(s.begin(),s.end());
            mp[s].push_back(strs[i]);
        }
        vector<vector<string> > vp;
 
       
        for(auto p:mp)
        {
            sort(p.second.begin(),p.second.end());
             vp.push_back(p.second);
        }
        return vp;
       
    }
};