-
Notifications
You must be signed in to change notification settings - Fork 30
/
anagrams.js
44 lines (41 loc) · 976 Bytes
/
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
// Given an array of strings, group anagrams together.
//
//
// For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
// Return:
//
// [
// ["ate", "eat","tea"],
// ["nat","tan"],
// ["bat"]
// ]
//
// Note: All inputs will be in lower-case.
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
const hashMap = {};
strs.forEach((str) => {
const val = generateKey(str);
if (hashMap[val]) {
hashMap[val].push(str);
} else {
hashMap[val] = [str];
}
});
const result = [];
for (let item in hashMap) {
result.push(hashMap[item]);
}
return result;
};
function generateKey (str) {
let result = 1;
for (let i = 0, l = str.length; i < l; i++) {
let n = str[i].charCodeAt() - 'a'.charCodeAt() + 1;
result = result * (n*n + n + 41) % 2147483647;
}
return result;
}