-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroup_Anagrams.java
More file actions
38 lines (33 loc) · 1019 Bytes
/
Copy pathGroup_Anagrams.java
File metadata and controls
38 lines (33 loc) · 1019 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
36
37
38
49. Group Anagrams
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
for(String str : strs){
// 将单词按字母排序
char[] carr = str.toCharArray();
Arrays.sort(carr);
String key = new String(carr);
List<String> list = map.get(key);
if(list == null){
list = new ArrayList<String>();
}
list.add(str);
map.put(key, list);
}
List<List<String>> res = new ArrayList<List<String>>();
for(String key : map.keySet()){
List<String> curr = map.get(key);
res.add(curr);
}
return res;
}
}