-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
70 lines (69 loc) · 1.45 KB
/
index.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* @lc app=leetcode id=49 lang=javascript
*
* [49] Group Anagrams
*
* https://leetcode.com/problems/group-anagrams/description/
*
* algorithms
* Medium (44.27%)
* Total Accepted: 294.4K
* Total Submissions: 660.1K
* Testcase Example: '["eat","tea","tan","ate","nat","bat"]'
*
* 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.
*
*
*/
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
const charsMap = {};
strs.forEach((str) => {
const key = str.split('').sort((a, b) => {
if (a > b) {
return -1;
}
if (a === b) {
return 0;
}
return 1;
}).join('');
if (charsMap[key]) {
charsMap[key].push(str);
} else {
charsMap[key] = [str];
}
});
const result = [];
for (let key in charsMap) {
result.push(charsMap[key]);
}
return result;
};
console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));
module.exports = {
id:'49',
title:'Group Anagrams',
url:'https://leetcode.com/problems/group-anagrams/description/',
difficulty:'Medium',
}