-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path49.group-anagrams.java
More file actions
36 lines (29 loc) · 842 Bytes
/
49.group-anagrams.java
File metadata and controls
36 lines (29 loc) · 842 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
26
27
28
29
30
31
32
33
34
35
/*
* @lc app=leetcode id=49 lang=java
*
* [49] Group Anagrams
*/
// @lc code=start
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<>();
if (strs.length == 0) {
return result;
}
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
char[] curr = strs[i].toCharArray();
Arrays.sort(curr);
String afterSort = String.valueOf(curr);
if (!map.containsKey(afterSort)) {
map.put(afterSort, new ArrayList<>());
}
map.get(afterSort).add(strs[i]);
}
for (String key : map.keySet()) {
result.add(map.get(key));
}
return result;
}
}
// @lc code=end