-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroupAnagrams.java
37 lines (29 loc) · 1017 Bytes
/
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
import java.util.*;
public class GroupAnagrams {
public static void main(String[] args) {
String[] s = {"abc", "bac", "cab"};
GroupAnagrams o1 = new GroupAnagrams();
System.out.print(o1.findAnagrams(s));
}
public List<List<String>> findAnagrams (String[] s) {
List<List<String>> res = new ArrayList<>();
Map<String, List<String >> mp = new HashMap<>();
for (String value : s) {
char[] str = value.toCharArray();
Arrays.sort(str);
String current = String.valueOf(str);
if (mp.get(current) != null) {
List<String> a = mp.get(current);
a.add(value);
mp.put(current, a);
} else {
List<String> a = new ArrayList<>();
mp.put(current, a);
}
for (Map.Entry<String, List<String>> en : mp.entrySet()) {
res.add(en.getValue());
}
}
return res;
}
}