-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
25 lines (23 loc) · 795 Bytes
/
Copy pathGroupAnagrams.java
File metadata and controls
25 lines (23 loc) · 795 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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/*
* https://leetcode.com/problems/group-anagrams/
*/
public class GroupAnagrams {
public List<List<String>> groupAnagrams(String[] strs) {
return new ArrayList<>(Arrays.stream(strs)
.collect(Collectors.groupingBy(s -> {
char[] chars = s.toCharArray();
Arrays.sort(chars);
return new String(chars);
}))
.values());
}
public static void main(String[] args) {
System.out.println(new GroupAnagrams().groupAnagrams(
new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}
)); // [[eat, tea, ate], [bat], [tan, nat]]
}
}