Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        
        for (String s:strs) {
            String ss = sortString(s);
            if (map.containsKey(ss)) {
                map.get(ss).add(s);
            } else {
                map.put(ss, new ArrayList<String>(Arrays.asList(s)));
            }
        }
        
        return new ArrayList<List<String>>(map.values());
    }
    
    private String sortString(String s) {
        return s.chars().sorted().collect(
            StringBuilder::new, StringBuilder::appendCodePoint,StringBuilder::append
        ).toString();
    }
}