-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode_00049.java
More file actions
71 lines (65 loc) · 2.08 KB
/
LeetCode_00049.java
File metadata and controls
71 lines (65 loc) · 2.08 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
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
package com.github.jerring.leetcode;
import java.util.*;
public class LeetCode_00049 {
// public List<List<String>> groupAnagrams(String[] strs) {
// if (strs.length == 0) {
// return new ArrayList<>();
// }
// Map<String, List<String>> map = new HashMap<>();
// for (String s : strs) {
// char[] cs = s.toCharArray();
// Arrays.sort(cs);
// String key = String.valueOf(cs);
// if (!map.containsKey(key)) {
// map.put(key, new ArrayList<>());
// }
// map.get(key).add(s);
// }
// return new ArrayList<>(map.values());
// }
// public List<List<String>> groupAnagrams(String[] strs) {
// if (strs.length == 0) {
// return new ArrayList<>();
// }
// Map<String, List<String>> map = new HashMap<>();
// for (String s : strs) {
// String id = getID(s);
// if (!map.containsKey(id)) {
// map.put(id, new ArrayList<>());
// }
// map.get(id).add(s);
// }
// return new ArrayList<>(map.values());
// }
//
// private String getID(String s) {
// int[] cnt = new int[26];
// for (char c : s.toCharArray()) {
// ++cnt[c - 'a'];
// }
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 26; ++i) {
// sb.append('#').append(cnt[i]);
// }
// return sb.toString();
// }
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0) {
return new ArrayList<>();
}
Map<Integer, List<String>> map = new HashMap<>();
for (String s : strs) {
int id = getID(s);
List<String> list = map.computeIfAbsent(id, k -> new ArrayList<>());
list.add(s);
}
return new ArrayList<>(map.values());
}
private int getID(String s) {
int[] cnt = new int[26];
for (char c : s.toCharArray()) {
++cnt[c - 'a'];
}
return Arrays.hashCode(cnt);
}
}