An intuitive and quick solution


  • 0
    R

    public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
    String copy, sorted;
    int i;
    char chars[];
    List<String> list;
    List<Integer> intList;
    List x;
    HashMap<String,List<String>> hm=new HashMap<String,List<String>>();

        for( i=0;i<strs.length;i++){
            chars=strs[i].toCharArray();
            Arrays.sort(chars);
            sorted=new String(chars);
            copy=sorted;
            if(hm.containsKey(copy)){
                x=hm.get(copy);
                x.add(strs[i]);
                hm.put(copy,x);
            }
            else{
                list=new ArrayList<String>();
                list.add(strs[i]);
                hm.put(copy,list);
            }
        }
        
        List<List<String>> lists=new ArrayList<List<String>>();
        
        for(List l:hm.values()){
            lists.add(l);
        }
       
        return lists;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.