forked from dipsdeepak11/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path049_Group_Anagrams.java
79 lines (73 loc) · 2.41 KB
/
049_Group_Anagrams.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
/**
Solution 1: HashMap
时间复杂度nk, 空间复杂度n (k为word长度)
1. 将word转化成int[],相当于排序。
2. 将int[]重新组成word,再用HashMap归类。
Solution 2: HashMap + Sort
时间复杂度nklogk, 空间复杂度n (k为word长度)
1. 讲word转化成char[], 用Arrays.sort直接排序。
*/
/**Solution 1 */
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<>();
if(strs == null || strs.length == 0){
return result;
}
int[][] record = new int[strs.length][256];
for(int i = 0; i < strs.length; i++){
String str = strs[i];
for(int j = 0; j < str.length(); j++){
char c = str.charAt(j);
record[i][c]++;
}
}
Map<String, List<String>> map = new HashMap<>();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < record.length; i++){
int[] asc = record[i];
for(int j = 0; j < asc.length; j++){
if(asc[j] > 0){
sb.append(asc[j]);
sb.append((char) j);
}
}
if(map.containsKey(sb.toString())){
map.get(sb.toString()).add(strs[i]);
}else{
map.put(sb.toString(), new ArrayList<>());
map.get(sb.toString()).add(strs[i]);
}
sb = new StringBuilder();
}
for(String key : map.keySet()){
result.add(map.get(key));
}
return result;
}
}
/**Solution 2 */
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<>();
if(strs == null || strs.length == 0){
return result;
}
HashMap<String, List<String>> map = new HashMap<>();
for(String str : strs){
char[] cs = str.toCharArray();
Arrays.sort(cs);
String hashStr = String.valueOf(cs);
if(map.containsKey(hashStr)){
map.get(hashStr).add(str);
}else{
map.put(hashStr, new ArrayList<>());
map.get(hashStr).add(str);
}
}
for(String hashStr : map.keySet()){
result.add(map.get(hashStr));
}
return result;
}
}