-
Notifications
You must be signed in to change notification settings - Fork 0
/
GroupAnagrams49.java
81 lines (70 loc) · 2.09 KB
/
GroupAnagrams49.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.util.*;
//https://leetcode.com/problems/group-anagrams/
public class GroupAnagrams49 {
public List<List<String>> groupAnagrams(String[] strs) {
//boundary
if (strs == null || strs.length == 0)
return new ArrayList<List<String>>();
Map<String, List<String>> map = new HashMap<String , List<String>>();
for (int i = 0; i < strs.length; i++) {
char[]temp = strs[i].toCharArray();
Arrays.sort(temp);
// String strKey = temp.toString();
String strKey = new String(temp);
if (!map.containsKey(strKey)) {
map.put(strKey,new ArrayList<String>());
}
map.get(strKey).add(strs[i]);
}
return new ArrayList<List<String>>(map.values());
}
public static void main (String[] args) {
GroupAnagrams49 obj = new GroupAnagrams49();
String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
System.out.print(obj.groupAnagrams(strs));
}
}
//20181218第一版本
//import java.util.*;
//
////https://leetcode.com/problems/group-anagrams/
//public class GroupAnagrams49 {
//
// public List<List<String>> groupAnagrams(String[] strs) {
// //边界条件
// if (strs == null || strs.length == 0)
// return new ArrayList<List<String>>();
//
// Map<String, List<String>> map = new HashMap<String, List<String>>();
// List<String> keys = new ArrayList();
// List<List<String>> result = new ArrayList<List<String>>();
//
// for (int i = 0; i < strs.length; i++) {
// char[]temp = strs[i].toCharArray();
// Arrays.sort(temp);
// String strKey = temp.toString();//此处 变换的不对
// System.out.print(strKey);
// if (!map.containsKey(strKey)) {
// map.put(strKey,new ArrayList<String>());
// keys.add(strKey);
// }
// map.get(strKey).add(strs[i]);
// System.out.print(map);
// }
//
// for (int i = 0; i < keys.size(); i++){
// System.out.print(map.get(keys.get(i)));
// result.add(map.get(keys.get(i)));
// }
//
// return result;
// }
//
// public static void main (String[] args) {
//
// GroupAnagrams49 obj = new GroupAnagrams49();
// String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
// System.out.print(obj.groupAnagrams(strs));
//
// }
//}