Skip to content

Commit 98b697f

Browse files
committed
add Group Anagrams solution
1 parent e42273d commit 98b697f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

group-anagrams/HoonDongKang.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* [Problem]: [49] Group Anagrams
3+
*
4+
* (https://leetcode.com/problems/group-anagrams/description/)
5+
*/
6+
function groupAnagrams(strs: string[]): string[][] {
7+
//시간복잡도 O(n * w log w)
8+
//공간복잡도 O(n * w)
9+
function mappedFunc(strs: string[]): string[][] {
10+
const map = new Map<string, string[]>();
11+
12+
for (let str of strs) {
13+
let sorted = [...str].sort().join("");
14+
15+
map.set(sorted, [...(map.get(sorted) ?? []), str]);
16+
}
17+
18+
return [...map.values()];
19+
}
20+
21+
//시간복잡오 O(n)
22+
//공간복잡도 O(n * w)
23+
function hashedMappedFunc(strs: string[]): string[][] {
24+
const map = new Map<string, string[]>();
25+
26+
for (let str of strs) {
27+
const count: number[] = new Array(26).fill(0);
28+
29+
for (const char of str) {
30+
count[char.charCodeAt(0) - 97]++;
31+
}
32+
33+
const key = count.join("#");
34+
map.set(key, [...(map.get(key) ?? []), str]);
35+
}
36+
37+
return [...map.values()];
38+
}
39+
return hashedMappedFunc(strs);
40+
}

0 commit comments

Comments
 (0)