-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
executable file
·42 lines (36 loc) · 953 Bytes
/
Copy pathGroupAnagrams.java
File metadata and controls
executable file
·42 lines (36 loc) · 953 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
39
40
41
42
import java.util.*;
/**
* Given an array of strings, group anagrams together.
* <p>
* For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
* Return:
* <p>
* [
* ["ate", "eat","tea"],
* ["nat","tan"],
* ["bat"]
* ]
* Note: All inputs will be in lower-case.
* <p>
* Accepted.
*/
public class GroupAnagrams {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> results = new ArrayList<>();
if (strs.length == 0) {
return results;
}
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
String key = String.valueOf(chars);
if (!map.containsKey(key)){
map.put(key, new ArrayList<>());
}
map.get(key).add(s);
}
results.addAll(map.values());
return results;
}
}