Skip to content

Commit 091d40a

Browse files
committed
Solve the problem #49
1 parent 9af3d72 commit 091d40a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package org.sean.array;
2+
3+
import java.util.*;
4+
5+
/** * 49. Group Anagrams */
6+
public class AnagramSorter {
7+
private int[] array = new int[26];
8+
9+
public List<List<String>> groupAnagrams(String[] strs) {
10+
if (strs == null || strs.length == 0) return Collections.emptyList();
11+
12+
HashMap<String, List<String>> map = new HashMap<>();
13+
14+
String s = strs[0];
15+
List<String> elems = new LinkedList<>();
16+
elems.add(s);
17+
18+
if (strs.length == 1) {
19+
return Arrays.asList(elems);
20+
}
21+
22+
String key = extractCountInfo(s);
23+
map.put(key, elems);
24+
25+
for (int i = 1; i < strs.length; i++) {
26+
String str = strs[i];
27+
String k = extractCountInfo(str);
28+
if (map.containsKey(k)) {
29+
map.get(k).add(str);
30+
} else {
31+
List<String> strValues = new LinkedList<>();
32+
strValues.add(str);
33+
map.put(k, strValues);
34+
}
35+
}
36+
37+
return new LinkedList<>(map.values());
38+
}
39+
40+
// Retrieves the character count info e.g '1a3b1c7z'
41+
private String extractCountInfo(String s) {
42+
Arrays.fill(array, 0);
43+
44+
for (int m = 0; m < s.length(); m++) {
45+
array[s.charAt(m) - 'a'] += 1;
46+
}
47+
48+
StringBuilder builder = new StringBuilder();
49+
for (int i = 0; i < array.length; i++) {
50+
if (array[i] > 0) {
51+
builder.append(array[i]).append((char) ('a' + i));
52+
}
53+
}
54+
return builder.toString();
55+
}
56+
}

0 commit comments

Comments
 (0)