Skip to content

Commit 1e095f7

Browse files
committed
solve: group anagrams
1 parent 211ac1b commit 1e095f7

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

โ€Žgroup-anagrams/wogha95.jsโ€Ž

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* TC: O(N * S)
3+
* SC: O(N)
4+
* N: strs.length, S: strs[i].length
5+
*
6+
* ํ’€์ด
7+
* ์ฃผ์–ด์ง„ ๋ฐฐ์—ด strs์˜ ๊ฐ ์›์†Œ์˜ ํ‚ค๋ฅผ ๊ตฌํ•ด์„œ ๊ฐ™์€ ์›์†Œ๋ผ๋ฆฌ ๋ฌถ์–ด ์ •๋‹ต์„ ์ฐพ๋Š”๋‹ค.
8+
* ํ‚ค ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์˜ ์‚ฌ์šฉ๋œ ์•ŒํŒŒ๋ฒณ ๊ฐฏ์ˆ˜์ด๋‹ค.
9+
*/
10+
11+
/**
12+
* @param {string[]} strs
13+
* @return {string[][]}
14+
*/
15+
var groupAnagrams = function (strs) {
16+
// 1. ํ‚ค๋ฅผ ์ €์žฅํ•  Map
17+
const keyMap = new Map();
18+
19+
for (const str of strs) {
20+
// 2. ํ‚ค๋ฅผ ๊ตฌํ•ด์„œ ๋™์ผํ•œ ํ‚ค๋ฉด ๊ฐ™์€ ๊ฐ’(๋ฐฐ์—ด)์— ์ถ”๊ฐ€ํ•œ๋‹ค.
21+
const key = generateKey(str);
22+
23+
if (keyMap.has(key)) {
24+
keyMap.get(key).push(str);
25+
} else {
26+
keyMap.set(key, [str]);
27+
}
28+
}
29+
30+
// 3. ํ‚ค๋ฅผ ์ €์žฅํ•œ Map์˜ ๊ฐ’๋“ค์„ ๋ชจ์•„ ์ •๋‹ต์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
31+
const result = [];
32+
33+
for (const v of keyMap.values()) {
34+
result.push(v);
35+
}
36+
37+
return result;
38+
39+
// ํ‚ค ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜
40+
function generateKey(str) {
41+
// ๊ฐ ์•ŒํŒŒ๋ฒณ์ด ๋ช‡๊ฐœ ๋“ฑ์žฅํ–ˆ๋Š”์ง€ ๊ธฐ๋กํ•  ๋ฐฐ์—ด
42+
const usedCount = new Array(26).fill(0);
43+
44+
for (const s of str) {
45+
// ์•„์Šคํ‚ค์ฝ”๋“œ๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ index๋ฅผ ๊ตฌํ•œ๋‹ค.
46+
usedCount[s.charCodeAt() - 97] += 1;
47+
}
48+
49+
return usedCount.join(",");
50+
}
51+
};

0 commit comments

Comments
ย (0)