/
Solution.java
executable file
·49 lines (44 loc) · 1.38 KB
/
Solution.java
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
import java.util.*;
public class Solution {
public List<String> anagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String i : strs) {
String keys;
char[] tmp = i.toCharArray();
Arrays.sort(tmp);
keys = new String(tmp);
List<String> tmplist;
if (map.containsKey(keys)) {
tmplist = map.get(keys);
} else {
tmplist = new ArrayList<>();
}
tmplist.add(i);
map.put(keys, tmplist);
}
List<String> res = new ArrayList<>();
for (String i : map.keySet()) {
List<String> tmplist2 = map.get(i);
if (tmplist2.size() > 1)
res.addAll(tmplist2);
}
return res;
}
}
public class Solution {
public List<String> anagrams(String[] strs) {
return Arrays.stream(strs)
.collect(Collectors.groupingBy(
k -> {
char[] w = k.toCharArray();
Arrays.sort(w);
return new String(w);
}
))
.values()
.stream()
.filter(v -> v.size() > 1)
.flatMap(v -> v.stream())
.collect(Collectors.toList());
}
}