Skip to content

Commit a3328d7

Browse files
committed
group-anagrams solution
1 parent 9c736ad commit a3328d7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

group-anagrams/lhc0506.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string[][]}
4+
*/
5+
var groupAnagrams = function(strs) {
6+
const A_ASCII = 'a'.charCodeAt();
7+
8+
const anagramMap = new Map();
9+
10+
for (const str of strs) {
11+
const counter = new Array(26).fill(0);
12+
13+
for (let i = 0; i < str.length; i++) {
14+
counter[str.charCodeAt(i) - A_ASCII]++;
15+
}
16+
17+
let key = '';
18+
for (let i = 0; i < 26; i++) {
19+
if (counter[i] > 0) {
20+
key += String.fromCharCode(i + A_ASCII) + counter[i];
21+
}
22+
}
23+
24+
if (!anagramMap.has(key)) {
25+
anagramMap.set(key, []);
26+
}
27+
anagramMap.get(key).push(str);
28+
}
29+
30+
return Array.from(anagramMap.values());
31+
};
32+
33+
// 시간 복잡도: O(n), 공간 복잡도: O(n)

0 commit comments

Comments
 (0)