-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathgroupAnagrams.java
More file actions
25 lines (21 loc) · 798 Bytes
/
groupAnagrams.java
File metadata and controls
25 lines (21 loc) · 798 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution
{
public List<List<String>> groupAnagrams(String[] strs)
{
HashMap<String, List<String>> groups = new HashMap<>();
for (String s : strs)
{
// [1] compute letter frequencies
char[] hash = new char[26];
s.chars().forEachOrdered(ch -> hash[ch-'a'] += 1);
// [2] smart way to obtain a hashable key for a map
String hashKey = String.valueOf(hash);
// [3] update group
if (!groups.containsKey(hashKey))
groups.put(hashKey, new ArrayList<>());
groups.get(hashKey).add(s);
}
// [4] nice one-liner to extract a list of values from map
return new ArrayList<>(groups.values());
}
}