-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroupAnagram.js
More file actions
40 lines (33 loc) · 844 Bytes
/
groupAnagram.js
File metadata and controls
40 lines (33 loc) · 844 Bytes
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
36
37
38
39
40
/*
49. Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
*/
let strs = ["eat","tea","tan","ate","nat","bat"]
function groupAnagrams(strs){
//Sort the anagrams
let sorted = strs.map((strs) => strs.split("").sort().join(""))
let map = {}
for(let i = 0; i<strs.length; i++){
if(!map[sorted]){
map[sorted[i]] = [strs[i]]
}
else {
map[sorted[i]].push(strs[i])
}
}
return Object.values(map)
}
console.log(groupAnagrams(strs))
/**
var groupAnagrams = function(strs) {
const map = new Map();
for (let word of strs) {
const key = word.split('').sort().join('');
if (!map.has(key)) {
map.set(key, []);
}
map.get(key).push(word);
}
return Array.from(map.values());
};
*/