Easy to understand JAVA solution using HashMaps(Edited)


  • 6
    J
    public class Solution {
       public List<List<String>> groupAnagrams(String[] strs) {
           List<List<String>>result= new ArrayList<>();
           Map<String,List<String>> map = new HashMap<String,List<String>>();
     
           for(String s:strs)
         {
               char[]c= s.toCharArray(); 
               Arrays.sort(c);                  
         
         //all Anagrams will be the same string if sorted  (tea,eat -->aet) , which serves as our key
             
             String keyStr= String.valueOf(c);
             if (!map.containsKey(keyStr)) map.put(keyStr, new ArrayList<String>());
             map.get(keyStr).add(s);
          }
     
      //All the key value entries are stored in an entrySet which helps us return those values that have a key corresponding to it
     
         for (Map.Entry<String, List<String>> entry : map.entrySet()) {
          
               List<String> values = entry.getValue();
    
               //since we want lexicographic order of the result, we sort the list
               Collections.sort(values);               
    
               result.add(values);
          }
    
         return result;   
      }
    }

  • 0
    A

    Just a suggestion: Sort each small group would be faster when you sort the whole input List<String> at the very beginning.


  • 0
    J

    Can you tell me a little more in detail on what you suggest?


  • 0
    A

    Well, not a big deal, I mean you can sort each anagram group in your last for loop.


  • 0
    J

    Thank you so much for the suggestion, it improved the performance and i have made the same changes in my code.


  • 0
    K

    You do not judge the argument called strs is whether null or not so that it can generate NullPointerException.And you can assign length of List called result to the length of array of Strings called strs at the time of initializing,it can keep the list from dynamically expand its length,because during this process it use Arrays.copyOf.it can save a little more time,i have tried it(beat 7% than the way you do)


  • 0
    K

    I just begin to read the problem and i am finding a better way to solve it beacause the way i improve yours resolution later just beat people of 80%.


Log in to reply
 

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