Java Simple Solution with Explanation


  • 0

    Explanation:
    The key of HashTable should be sorted string, since anagrams have the same key. Before added into result, we need to sort anagrams based on Alphabetical Order.

    public class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            Map<String, List<String>> map = new HashMap<>();
            
            for (String s : strs){
                char[] c = s.toCharArray();
                Arrays.sort(c);
                String sorted_s = String.valueOf(c);
                
                List<String> list = map.getOrDefault(sorted_s, new ArrayList<String>());
                list.add(s);
                map.put(sorted_s, list);
            }
            
            List<List<String>> result = new ArrayList<>();
            
            for (List<String> list : map.values()){
                Collections.sort(list);
                result.add(list);
            }
            
            return result;
        }
    }
    

Log in to reply
 

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