forked from kdn251/interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroupAnagrams.java
More file actions
41 lines (24 loc) · 1021 Bytes
/
groupAnagrams.java
File metadata and controls
41 lines (24 loc) · 1021 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
// 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) {
if(strs == null || strs.length == 0) return new ArrayList<List<String>>();
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
Arrays.sort(strs);
for(String s : strs) {
char[] characters = s.toCharArray();
Arrays.sort(characters);
String key = String.valueOf(characters);
if(!map.containsKey(key)) map.put(key, new ArrayList<String>());
map.get(key).add(s);
}
return new ArrayList<List<String>>(map.values());
}
}