-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMakingAnagrams.js
58 lines (45 loc) · 1.24 KB
/
MakingAnagrams.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
// Solution 1
function makingMap(str) {
const map = new Map();
for (const item of str) {
map.has(item) ? map.set(item, map.get(item) + 1) : map.set(item, 1);
}
return map;
}
function makingAnagrams(s1, s2) {
const s1Map = makingMap(s1);
const s2Map = makingMap(s2);
let deletedAlphabetCount = 0;
for (const [alphabet, count] of s1Map) {
s2Map.has(alphabet)
? (deletedAlphabetCount += Math.abs(count - s2Map.get(alphabet)))
: (deletedAlphabetCount += count);
}
for (const [alphabet, count] of s2Map) {
if (!s1Map.has(alphabet)) {
deletedAlphabetCount += count;
}
}
return deletedAlphabetCount;
}
// Solution 2
function makingMap(str) {
const map = new Map();
for (const item of str) {
map.has(item) ? map.set(item, map.get(item) + 1) : map.set(item, 1);
}
return map;
}
function makingAnagrams(s1, s2) {
const s1Map = makingMap(s1);
const s2Map = makingMap(s2);
let commonAlphabetCount = 0;
for (const [alphabet, count] of s1Map) {
if (s2Map.has(alphabet)) {
commonAlphabetCount +=
count > s2Map.get(alphabet) ? s2Map.get(alphabet) : count;
}
}
const deletedAlphabetCount = s1.length + s2.length - commonAlphabetCount * 2;
return deletedAlphabetCount;
}