-
Notifications
You must be signed in to change notification settings - Fork 15
/
Anagram.js
54 lines (42 loc) · 1.13 KB
/
Anagram.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
function anagram(array) {
var dictionary = {},
string,
result = [],
n = array.length,
i;
for (i = 0; i < n; i++) {
string = array[i].split('').sort().join('');
if (dictionary[string] === undefined) {
dictionary[string] = {};
dictionary[string][array[i]] = true;
} else if (!dictionary[string][array[i]]) {
dictionary[string][array[i]] = true;
}
}
for (i in dictionary) {
result.push(Object.keys(dictionary[i]));
}
return result;
}
var input = ["cab", "cz", "abc", "bca", "zc"];
console.log(anagram(input));
function groupAnagram(array) {
var n = array.length,
i,
dict = {},
sortedString,
result = [];
for (i = 0; i < n; i++) {
sortedString = array[i].split('').sort().join('');
if (dict[sortedString] === undefined) {
dict[sortedString] = {};
}
dict[sortedString][array[i]] = true;
}
for (i in dict) {
result.push(Object.keys(dict[i]));
}
return result;
}
var input = ["star", "rats", "star", "car", "arc", "arts"];
console.log(groupAnagram(input));