Simple java solution


  • 11
    H
    public List<List<String>> groupAnagrams(String[] strs) {
    	List<List<String>> res = new ArrayList<>();
        HashMap<String, List<String>> map = new HashMap<>();
        
        Arrays.sort(strs);
        for (int i = 0; i < strs.length; i++) {
        	String temp = strs[i];
        	char[] ch = temp.toCharArray();
        	Arrays.sort(ch);
        	if (map.containsKey(String.valueOf(ch))) {
        		map.get(String.valueOf(ch)).add(strs[i]);
        	} else {
        		List<String> each = new ArrayList<>();
        		each.add(strs[i]);
        		map.put(String.valueOf(ch), each);
        	}
        }
        for (List<String> item: map.values()) {
        	res.add(item);
        }
        return res;
    }

  • 0
    W

    We don't need to specify the Comparator for Collections.sort(List<String>);


  • 9
    P

    You can do a

    Arrays.sort(strs)
    

    before the first for-loop, so that you don't need to worry about the lexicographic orders later


  • 0
    H

    yep. thanks!


  • 1
    Z

    Guess this can be simplified ?

        for (List<String> item: map.values()) {
        	res.add(item);
        }
    

    into

    return new ArrayList(map.values())
    

  • 2
    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.