Time: $O(NK\log{K})$ where $K$ is the maximum length of a string. Space: $O(NK)$
Categorize by Count
Count a string’s characters and generate a key like #1#2#3#4....
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public List<List<String>> groupAnagrams(String[] strs) { if (strs.length == 0) returnnew ArrayList(); Map<String, List> ans = new HashMap<String, List>(); int[] count = newint[26]; for (String s : strs) { Arrays.fill(count, 0); for (char c : s.toCharArray()) count[c - 'a']++;
StringBuilder sb = new StringBuilder(""); for (int i = 0; i < 26; i++) { sb.append('#'); sb.append(count[i]); } String key = sb.toString(); if (!ans.containsKey(key)) ans.put(key, new ArrayList()); ans.get(key).add(s); } returnnew ArrayList(ans.values()); }