-
Notifications
You must be signed in to change notification settings - Fork 4
/
Solution.java
39 lines (36 loc) · 1.11 KB
/
Solution.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
package _049;
import java.util.*;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/10/18
* desc :
* </pre>
*/
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) return Collections.emptyList();
List<List<String>> list = new ArrayList<>();
Map<String, Integer> hash = new HashMap<>();
int i = 0;
for (String str : strs) {
char[] c = str.toCharArray();
Arrays.sort(c);
String sortStr = String.valueOf(c);
if (!hash.containsKey(sortStr)) {
hash.put(sortStr, i++);
List<String> sub = new ArrayList<>();
sub.add(str);
list.add(sub);
} else {
list.get(hash.get(sortStr)).add(str);
}
}
return list;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}));
}
}