-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgroup-anagrams.js
35 lines (26 loc) · 891 Bytes
/
group-anagrams.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// https://leetcode.com/problems/group-anagrams/
import { areEquivalent } from "./utils/array.js";
const groupAnagrams = (strs) => {
const groups = { };
for (let str of strs) {
const key = str.split('').sort().join('');
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(str);
}
return Object.values(groups);
}
let strs, expected, actual;
strs = ["eat","tea","tan","ate","nat","bat"];
expected = [["bat"],["nat","tan"],["ate","eat","tea"]];
actual = groupAnagrams(strs);
console.assert(areEquivalent(expected, actual), '%o', { strs, expected, actual });
strs = ["a"];
expected = [["a"]];
actual = groupAnagrams(strs);
console.assert(areEquivalent(expected, actual), '%o', { strs, expected, actual });
strs = [''];
expected = [['']];
actual = groupAnagrams(strs);
console.assert(areEquivalent(expected, actual), '%o', { strs, expected, actual });