-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagramGrouper.java
More file actions
52 lines (40 loc) · 1.29 KB
/
Copy pathAnagramGrouper.java
File metadata and controls
52 lines (40 loc) · 1.29 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
51
52
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class AnagramGrouper {
public static List<List<String>> groupAnagrams(String[] words) {
if (words == null || words.length == 0) {
return new ArrayList<>();
}
Map<String, List<String>> anagramGroups = new LinkedHashMap<>();
for (String word : words) {
if (word == null) {
continue;
}
String key = createAnagramKey(word);
anagramGroups
.computeIfAbsent(key, ignored -> new ArrayList<>())
.add(word);
}
return new ArrayList<>(anagramGroups.values());
}
private static String createAnagramKey(String word) {
char[] characters = word.toLowerCase().toCharArray();
Arrays.sort(characters);
return new String(characters);
}
public static void main(String[] args) {
String[] words = {
"eat",
"tea",
"tan",
"ate",
"nat",
"bat"
};
List<List<String>> groupedAnagrams = groupAnagrams(words);
groupedAnagrams.forEach(System.out::println);
}
}