-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
82 lines (69 loc) · 2.19 KB
/
Copy pathGroupAnagrams.java
File metadata and controls
82 lines (69 loc) · 2.19 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
72
73
74
75
76
77
78
79
80
81
82
// Source : https://leetcode.com/problems/group-anagrams/
// Author : cornprincess
// Date : 2020-04-07
/*****************************************************************************************************
*
* Given an array of strings, group anagrams together.
*
* Example:
*
* Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
* Output:
* [
* ["ate","eat","tea"],
* ["nat","tan"],
* ["bat"]
* ]
*
* Note:
*
* All inputs will be in lowercase.
* The order of your output does not matter.
*
******************************************************************************************************/
package GroupAnagrams;
import java.util.*;
public class GroupAnagrams {
// Time Complexity: O(NKlogK)
// Space Complexity: O(NK)
public List<List<String>> sortedKeyHashMap(String[] strs) {
if (strs.length == 0) {
return new ArrayList<>();
}
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] charArray = str.toCharArray();
Arrays.sort(charArray);
String sortedStr = String.valueOf(charArray);
if (!map.containsKey(sortedStr)) {
map.put(sortedStr, new ArrayList<>());
}
map.get(sortedStr).add(str);
}
return new ArrayList<>(map.values());
}
// Time Complexity: O(NK)
// Space Complexity: O(NK)
public List<List<String>> countedKeyHashMap(String[] strs) {
if (strs.length == 0) {
return new ArrayList<>();
}
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
int[] count = new int[26];
for (char c : str.toCharArray()) {
count[c - 'a']++;
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 26; i++) {
stringBuilder.append('#').append(count[i]);
}
String key = stringBuilder.toString();
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(str);
}
return new ArrayList<>(map.values());
}
}