Skip to content

Commit 764f4a1

Browse files
committed
Group Anagrams
1 parent 835ce9f commit 764f4a1

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

group-anagrams/forest000014.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
Time Complexity: O(n)
3+
Space Complexity: O(n)
4+
*/
5+
class Solution {
6+
public List<List<String>> groupAnagrams(String[] strs) {
7+
Map<String, List<String>> map = new HashMap<>();
8+
9+
for (String str : strs) {
10+
int[] cnt = new int[26];
11+
for (int i = 0; i < str.length(); i++) {
12+
cnt[str.charAt(i) - 'a']++;
13+
}
14+
char[] chars = new char[str.length()];
15+
int idx = 0;
16+
for (int i = 0; i < 26; i++) {
17+
while (cnt[i] > 0) {
18+
chars[idx++] = (char)(i + 'a');
19+
cnt[i]--;
20+
}
21+
}
22+
String sorted = new String(chars);
23+
if (!map.containsKey(sorted)) {
24+
map.put(sorted, new ArrayList<>());
25+
}
26+
map.get(sorted).add(str);
27+
}
28+
29+
List<List<String>> ans = new ArrayList<>();
30+
for (String key : map.keySet()) {
31+
ans.add(new ArrayList<>());
32+
for (String str : map.get(key)) {
33+
ans.get(ans.size() - 1).add(str);
34+
}
35+
}
36+
37+
return ans;
38+
}
39+
}

0 commit comments

Comments
 (0)