-
Notifications
You must be signed in to change notification settings - Fork 130
/
Anagrams.js
44 lines (37 loc) · 914 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, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
*/
/**
* @param {string[]} strs
* @return {string[]}
*/
var anagrams = function(strs) {
var map = {},
len = strs.length,
curStr,
newArr,
sortedArr,
sortedStr,
result = [],
i;
for (i = 0; i < len; i++) {
curStr = strs[i];
sortedArr = curStr.split('');
sortedStr = sortedArr.sort().join('');
if (map.hasOwnProperty(sortedStr)) {
map[sortedStr].push(curStr);
} else {
newArr = [];
newArr.push(curStr);
map[sortedStr] = newArr;
}
}
len = map.length;
for (var key in map) {
if (map[key].length > 1) {
result = result.concat(map[key]);
}
}
return result;
};