Share my simple Java solution, pretty easy to understand


  • 9
    C

    I don't see this code needs any more explanation. Straightforward.

    public List<List<String>> groupAnagrams(String[] strs) {
      Arrays.sort(strs);
      HashMap<String, List<String>> hm = new HashMap<>();
      for(int i = 0; i < strs.length; i++){
        String currString = strs[i];
        char[] charArr = strs[i].toCharArray();
        Arrays.sort(charArr);
        String sortString = new String(charArr);
        List<String > tempList = hm.getOrDefault(sortString, new ArrayList<String>());
        tempList.add(currString);
        hm.put(sortString, tempList);
      }
      return new ArrayList<>(hm.values());
    }

  • 0
    R

    why "Arrays.sort(strs);"????
    Can you explain it ?


  • 0
    D

    follow the lexicographic order.


  • 0
    T
    This post is deleted!

  • 1
    T

    getOrDefault allocates unnecesary ArrayLists, worst case is when all of them are in the same group and there are many.


  • 0
    H

    Elegant !
    Cong!!!!!!!!!!!!!!!!!


  • 0
    Z

    List<String > tempList = hm.getOrDefault(sortString, new ArrayList<String>());
    is creating a lot ArrayList.

    Nice othert han that.


  • 0
    O

    You don't need first sort.


Log in to reply
 

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