-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathGroup_Anagrams.js
50 lines (38 loc) · 892 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
Group Anagrams
https://leetcode.com/problems/group-anagrams/description/
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
*/
var groupAnagrams = function(strs) {
var ret = [];
var hashMap = {};
for(var i = 0; i < strs.length; i++) {
const elem = strs[i];
const elemSorted = sortString(strs[i]);
if(hashMap[elemSorted]) {
hashMap[elemSorted].push(elem);
} else {
hashMap[elemSorted] = [elem];
}
}
for(key in hashMap)
ret.push(hashMap[key]);
return ret;
};
var sortString = function(str) {
if(str.length === 0)
return str;
return str.split("").sort().join("");
}
module.exports.groupAnagrams = groupAnagrams;