Skip to content

Commit e1ae708

Browse files
committed
group-anagrams
1 parent 1ce733b commit e1ae708

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

group-anagrams/jun0811.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string[][]}
4+
*/
5+
var groupAnagrams = function (strs) {
6+
const hashMap = new Map();
7+
const res = [];
8+
strs.forEach((str, index) => {
9+
const sortedStr = [...str].sort().join('');
10+
if (hashMap.has(sortedStr)) {
11+
hashMap.set(sortedStr, [...hashMap.get(sortedStr), index]);
12+
} else {
13+
hashMap.set(sortedStr, [index]);
14+
}
15+
});
16+
for (const [key, values] of hashMap) {
17+
const anagrams = values.map((v) => strs[v]);
18+
res.push(anagrams);
19+
}
20+
return res;
21+
};

0 commit comments

Comments
 (0)