-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
41 lines (40 loc) · 1.33 KB
/
Copy pathGroupAnagrams.java
File metadata and controls
41 lines (40 loc) · 1.33 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
35
36
37
38
39
40
41
public class GroupAnagrams{
public List<List<String>> groupAnagrams(String[] strs) {
ArrayList<List<String>> result = new ArrayList<List<String>>();
if(strs.length > 0){
HashMap<String, ArrayList<String>> m = new HashMap<String, ArrayList<String>>();
for(int i = 0; i < strs.length; i++){
String key = sort(strs[i]);
ArrayList<String> value = m.get(key);
if(value == null){
value = new ArrayList<String>();
value.add(strs[i]);
m.put(key, value);
} else {
value.add(strs[i]);
}
}
for(ArrayList<String> a : m.values()){
Collections.sort(a);
result.add(a);
}
}
return result;
}
// since chars in s are only from 'a' to 'z';
public String sort(String s){
char[] chars = s.toCharArray();
int[] count = new int[26];
char[] result = new char[chars.length];
for(char c : chars){
count[(int)c - 'a'] ++;
}
for(int i = 1; i < 26; i++){
count[i] += count[i - 1];
}
for(char c : chars){
result[--count[(int)c - 'a']] = c;
}
return new String(result);
}
}