-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroupAnagrams.java
48 lines (38 loc) · 1.05 KB
/
GroupAnagrams.java
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
43
44
45
46
47
48
package techQuestions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GroupAnagrams {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
List<List<String>> output = groupAnagrams(strs);
for (List l : output) {
System.out.println(l.toString());
}
}
public static List<List<String>> groupAnagrams(String[] strs) {
int[] count = new int[26];
Map<String, List> map = new HashMap<String, List>();
for (String s: strs) {
// initialize count for each string in strs
Arrays.fill(count, 0);
for (char c: s.toCharArray()) {
count[c - 'a']++;
}
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < 26; i++) {
sb.append('#');
sb.append(count[i]);
}
String key = sb.toString();
if (!map.containsKey(key)) {
map.put(key, new ArrayList());
}
map.get(key).add(s);
}
return new ArrayList(map.values());
}
}