-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
26 lines (20 loc) · 1.02 KB
/
GroupAnagrams.java
File metadata and controls
26 lines (20 loc) · 1.02 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
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// Create a map to group the anagrams, where the key is the sorted string.
Map<String, List<String>> anagramsMap = new HashMap<>();
// Iterate over each string in the array.
for (String str : strs) {
// Convert the string to a character array and sort it.
char[] charArray = str.toCharArray();
Arrays.sort(charArray);
// Create a new string from the sorted character array.
String sortedStr = new String(charArray);
// If the sorted string key is not present in the map, initialize it with an empty list.
anagramsMap.putIfAbsent(sortedStr, new ArrayList<>());
// Add the original string to the list associated with the sorted string key.
anagramsMap.get(sortedStr).add(str);
}
// Return the values of the map as a list of lists.
return new ArrayList<>(anagramsMap.values());
}
}