-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0049-group-anagrams.java
47 lines (38 loc) · 1.35 KB
/
0049-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
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> res = new HashMap<>();
for (String s : strs) {
int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 26; i++) {
sb.append('#');
sb.append(count[i]);
}
String key = sb.toString();
if (!res.containsKey(key)) {
res.put(key, new ArrayList<>());
}
res.get(key).add(s);
}
return new ArrayList<>(res.values());
}
}
-------------------------------------------------------------------------
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String word : strs) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
String sortedWord = new String(chars);
if (!map.containsKey(sortedWord)) {
map.put(sortedWord, new ArrayList<>());
}
map.get(sortedWord).add(word);
}
return new ArrayList<>(map.values());
}
}