forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0049-group-anagrams.ts
57 lines (44 loc) · 1.32 KB
/
0049-group-anagrams.ts
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
function groupAnagrams(strs: string[]): string[][] {
const hash: {
[key: string]: string[];
} = {};
strs.forEach((item, index) => {
let doesExist = false;
Object.keys(hash).forEach((key) => {
if (isAnagram(item, key)) {
hash[key].push(item);
doesExist = true;
}
});
if (!doesExist) {
hash[item] = [item];
}
});
console.log(hash);
return [...Object.keys(hash).map((k) => hash[k])];
}
console.log(groupAnagrams(['eat', 'ate', 'dog', 'pog']));
function isAnagram(s: string, t: string) {
if (s.length !== t.length) return false;
var first: Array<string | null> = s.split('');
const second = t.split('');
for (let i = 0; i < second.length; i++) {
const element = second[i];
let found = first.indexOf(element);
if (found !== -1) {
first[found] = null;
} else {
return false;
}
}
return true;
}
// Solution using map with reduce
function groupAnagrams(strs: string[]): string[][] {
const wordsMap = strs.reduce((map, str) => {
const sortedChars = [...str].sort().join('');
map[sortedChars] = (map[sortedChars] || []).concat(str);
return map;
}, {});
return Object.values(wordsMap);
}