Skip to content

Commit 54f4585

Browse files
Added GroupAnagrams (ignacio-chiazzo#17)
1 parent 675ad78 commit 54f4585

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

LeetcodeProblems/GroupAnagrams.js

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
https://leetcode.com/problems/group-anagrams/description/
3+
4+
Given an array of strings, group anagrams together.
5+
6+
Example:
7+
8+
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
9+
Output:
10+
[
11+
["ate","eat","tea"],
12+
["nat","tan"],
13+
["bat"]
14+
]
15+
Note:
16+
17+
All inputs will be in lowercase.
18+
The order of your output does not matter.
19+
*/
20+
21+
var groupAnagrams = function(strs) {
22+
var ret = [];
23+
var hashMap = {};
24+
for(var i = 0; i < strs.length; i++) {
25+
const elem = strs[i];
26+
const elemSorted = sortString(strs[i]);
27+
28+
if(hashMap[elemSorted]) {
29+
hashMap[elemSorted].push(elem);
30+
} else {
31+
hashMap[elemSorted] = [elem];
32+
}
33+
}
34+
35+
for(key in hashMap) {
36+
ret.push(hashMap[key]);
37+
}
38+
39+
return ret;
40+
};
41+
42+
var sortString = function(str) {
43+
if(str.length === 0) {
44+
return str;
45+
}
46+
47+
return str.split("").sort().join("");
48+
}
49+
50+
var main = function() {
51+
console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));
52+
}
53+
54+
module.exports.main = main;

0 commit comments

Comments
 (0)