Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: strs = {"eat","tea","tan","ate","nat","bat"}
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Approach

Java


public class GroupAnagrams {
    public static void main(String[] args) {
        String strs[] = { "eat""tea""tan""ate""nat""bat" };
        List<List<String>> res = groupAnagrams(strs);
        System.out.println(Arrays.asList(res));
    }

    static List<List<String>> groupAnagrams(String[] strs) {
        HashMap<StringList<String>> ump = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            String x = strs[i];
            char[] c = x.toCharArray();
            Arrays.sort(c);
            x = new String(c);

            if (ump.containsKey(x)) {
                List<Stringl = ump.get(x);
                l.add(strs[i]);
                ump.put(x, l);
            } else {
                List<Stringl = new ArrayList<String>();
                l.add(strs[i]);
                ump.put(x, l);
            }
        }
        List<List<String>> res = new ArrayList<List<String>>();
        for (String key : ump.keySet())
            res.add(ump.get(key));
        return res;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;


vector<vector<string>> groupAnagrams(vector<string>& strs
{
        unordered_map<string,vector<string>> ump;
        for(int i=0;i<strs.size();i++)
        {
            string x=strs[i];
            sort(x.begin(),x.end());
            ump[x].push_back(strs[i]);
        }
        vector<vector<string>> res;
        for(auto it=ump.begin();it!=ump.end();it++)
               res.push_back(it->second);
        return res;
 }
int main()
{
  vector<stringstrs ={"eat","tea","tan","ate","nat","bat"};
  vector<vector<string>> res=groupAnagrams(strs);
  cout<<"[";
  for(int i=0;i<res.size();i++)
    {
        cout<<"[";
        for(int j=0;j<res[i].size();j++)
           {
               cout<<res[i][j];
               if(j!=res[i].size()-1)
                  cout<<",";
           }
        cout<<"]";
        if(i!=res.size()-1)
          cout<<",";
    }
    cout<<"]";
}


No comments:

Post a Comment