35 ms java solution


  • 0
    S
    public class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
           Map<String, List<String>> mappings = new HashMap<>();
           List<String> list;
           for(String word : strs){
               char[] charsInStr = word.toCharArray();
               Arrays.sort(charsInStr);
               String sortedString = String.valueOf(charsInStr);
               if(mappings.containsKey(sortedString)){
                    list = mappings.get(sortedString);
               }else {
                    list = new ArrayList<>();
               }
               list.add(word);
               mappings.put(sortedString, list);
           }
           List<List<String>> output = new ArrayList<>();
           for(Map.Entry entry : mappings.entrySet()){
               output.add(((List<String>)entry.getValue()));
           }
           return output;
        }
    }
    

Log in to reply
 

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