-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroupAnagrams93.java
34 lines (27 loc) · 1.21 KB
/
GroupAnagrams93.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
import java.util.*;
public class GroupAnagrams93 {
public List<List<String>> groupAnagrams(String[] strs) {
// Create a map to hold the grouped anagrams
Map<String, List<String>> anagramGroups = new HashMap<>();
// Iterate through each string in the input array
for (String s : strs) {
// Sort the characters of the string to form a key
char[] charArray = s.toCharArray();
Arrays.sort(charArray);
String sortedString = new String(charArray);
// Add the original string to the corresponding list in the map
anagramGroups.putIfAbsent(sortedString, new ArrayList<>());
anagramGroups.get(sortedString).add(s);
}
// Return the values of the map as a list of lists
return new ArrayList<>(anagramGroups.values());
}
public static void main(String[] args) {
GroupAnagrams93 solution = new GroupAnagrams93();
// Test case
String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
List<List<String>> result = solution.groupAnagrams(strs);
// Print the result
System.out.println(result);
}
}