-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
69 lines (53 loc) · 1.52 KB
/
solution.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
/**
* @param {string[]} strs
* @return {string[][]}
*/
const groupAnagrams = (list) => {
// result,
// shift -> for i & k=i+1
// twice isAnagram just to check
// if we find one -> splice(index, 1)
// -> group.push(item) // until the end of the list
// until []
// let x = processWords(list, []);
// console.log("x")
// console.log(x)
return processWords(list, []);
}
const areTheyAnagrams = (word1, word2) => {
let char1 = (word1 || "0").split(""),
char2 = (word2 || "0").split("");
if (undefined === word2 || (word1 && word2 && (word1.length !== word2.length))) return false;
let map1 = createAnagramMap(char1), map2 = createAnagramMap(char2);
for (let i = 0; i < char1.length; i++) {
if (map1.get(char1[i]) !== map2.get(char1[i])) return false;
}
return true;
}
const createAnagramMap = (char) => {
let map = new Map();
for (let i = 0; i < char.length; i++) {
map.set(char[i], (map.has(char[i]) ? (map.get(char[i]) + 1) : 1))
}
return map;
}
const processWords = (list, groupList) => {
if (0 === list.length) {
return groupList;
}
let curr = list.shift(), tmpList = [...list], group = [];
group.push(curr);
while (0 < list.length) {
let next = list.shift();
if (areTheyAnagrams(curr, next)) {
group.push(next);
}
}
// Remove from tmpList that are added into the group
tmpList = tmpList.filter((elem) => {
return !group.includes(elem);
})
// process for groupList
groupList.push(group);
return processWords(tmpList, groupList);
}