-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
34 lines (32 loc) · 1.19 KB
/
Solution.java
File metadata and controls
34 lines (32 loc) · 1.19 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
package leetcode._49_;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> resultList = new ArrayList<>();
if (strs == null || strs.length == 0) {
return resultList;
}
Map<String,List<String>> groupsMap = new HashMap<>();
// 这里的 key 需要是 String,而不能使用数组,如果使用数组的话,key是内存地址,无法满足要求。
// value 存储的是这个组的字符串的 index
for (int i = 0; i < strs.length; i++) {
String str = strs[i];
char[] chars = str.toCharArray();
Arrays.sort(chars);
String s = String.valueOf(chars); // 排序后得到最新的字符串
if (groupsMap.containsKey(s)) {
groupsMap.get(s).add(str);
continue;
}
List<String> resultItem = new ArrayList<>();
groupsMap.put(s,resultItem);
resultItem.add(str);
resultList.add(resultItem);
}
return resultList;
}
}