-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
executable file
·42 lines (39 loc) · 1.24 KB
/
Solution.java
File metadata and controls
executable file
·42 lines (39 loc) · 1.24 KB
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
package $049;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/**
* @author Junlan Shuai[shuaijunlan@gmail.com].
* @date Created on 19:00 2017/10/24.
*/
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> lists= new LinkedList<>();
if(strs == null || strs.length == 0) {
return lists;
}
int length = strs.length;
HashMap<String, List<String>> map = new HashMap<>();
for (int i = 0; i < length; i++) {
char str[] = strs[i].toCharArray();
Arrays.sort(str);
if (map.containsKey(String.valueOf(str))) {
map.get(String.valueOf(str)).add(strs[i]);
} else {
LinkedList<String> list = new LinkedList<>();
list.add(strs[i]);
map.put(String.valueOf(str), list);
}
}
for (List<String> a : map.values()){
lists.add(a);
}
return lists;
}
public static void main(String[] args) {
String strs[] = {"eat", "tea", "tan", "ate", "nat", "bat"};
Solution solution = new Solution();
solution.groupAnagrams(strs);
}
}