-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGroupAnagrams.java
33 lines (30 loc) · 980 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
import java.util.*;
/**
* Created by cpacm on 2017/6/9.
*/
public class GroupAnagrams {
public static void main(String[] args) {
System.out.println(groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}));
}
public static List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ll = new ArrayList<>();
if (strs.length <= 0) return ll;
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
String sstr = sortStr(str);
if (map.containsKey(sstr)) {
map.get(sstr).add(str);
} else {
List<String> l = new ArrayList<>();
l.add(str);
map.put(sstr, l);
}
}
return new ArrayList<>(map.values());
}
public static String sortStr(String str) {
char[] cc = str.toCharArray();
Arrays.sort(cc);
return String.valueOf(cc);
}
}