Repository navigation
Expand file tree
/
Copy pathLeetCode49.java
More file actions
50 lines (45 loc) · 1.71 KB
/
Copy pathLeetCode49.java
File metadata and controls
50 lines (45 loc) · 1.71 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.*;
import java.util.stream.Collectors;
//49: group-anagrams
public class LeetCode49 {
//best one
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0)
return null;
return new ArrayList<>(Arrays.stream(strs).collect(Collectors.groupingBy(
st -> {
char[] chars = st.toCharArray();
Arrays.sort(chars);
return new String(chars);
})).values());
}
}
//CollectorsAndThen - once
class Solution2 {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0)
return null;
return Arrays.stream(strs).collect(Collectors.collectingAndThen(Collectors.groupingBy(
st -> {
char[] chars = st.toCharArray();
Arrays.sort(chars);
return new String(chars);
}), Map::values)).stream().toList();
}
}
//CollectorsAndThen() - Twice
class Solution3 {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0)
return null;
return Arrays.stream(strs)
.collect(Collectors.collectingAndThen(Collectors.collectingAndThen(Collectors.groupingBy(
st -> {
char[] chars = st.toCharArray();
Arrays.sort(chars);
return new String(chars);
}), Map::values), ArrayList::new));
}
}
}