-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
52 lines (41 loc) · 1.15 KB
/
GroupAnagrams.java
File metadata and controls
52 lines (41 loc) · 1.15 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
package string;
import java.util.*;
/**
* Description: https://leetcode.com/problems/group-anagrams
* Difficulty: Medium
*/
public class GroupAnagrams {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
String key = countHash(str);
List<String> words = map.computeIfAbsent(key, __ -> new ArrayList<>());
words.add(str);
}
return new ArrayList<>(map.values());
}
/**
* Time complexity: O(n * k)
* Space complexity: O(n * k)
*/
private String countHash(String str) {
int[] count = new int[26];
for (char c : str.toCharArray()) {
count[c - 'a']++;
}
StringBuilder sb = new StringBuilder();
for (int c : count) {
sb.append(c).append("#");
}
return sb.toString();
}
/**
* Time complexity: O(n * klog k)
* Space complexity: O(n * k)
*/
private String sortHash(String str) {
char[] arr = str.toCharArray();
Arrays.sort(arr);
return new String(arr);
}
}