Share my java solution, use sort and map


  • 0
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        
        Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
        
        for(String str : strs){
            char[] chs = str.toCharArray();
            Arrays.sort(chs);
            String s = String.valueOf(chs);
            
            if(! map.containsKey(s)){
                map.put(s, new ArrayList<String>());
            }
            
            map.get(s).add(str);
        }
        
        for(List<String> list : map.values()){
            res.add(list);
        }
        
        return res;
        
    }

Log in to reply
 

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