-
Notifications
You must be signed in to change notification settings - Fork 0
/
Anagram.js
87 lines (66 loc) · 1.64 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Solution 1
function makeMap(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 anagram(s) {
const half = s.length / 2;
let replacedCount = 0;
if (!Number.isInteger(half)) {
return -1;
}
const firstMap = makeMap(s.substring(0, half));
const secondMap = makeMap(s.substring(half));
for (const [item, _] of firstMap) {
while (secondMap.has(item)) {
firstMap.set(item, firstMap.get(item) - 1);
secondMap.set(item, secondMap.get(item) - 1);
if (firstMap.get(item) === 0) {
firstMap.delete(item);
break;
}
if (secondMap.get(item) === 0) {
secondMap.delete(item);
break;
}
}
}
for (const [_, count] of firstMap) {
replacedCount += count;
}
return replacedCount;
}
// Solution 2
function makeMap(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 anagram(s) {
const half = s.length / 2;
let replacedCount = 0;
if (!Number.isInteger(half)) {
return -1;
}
const firstMap = makeMap(s.substring(0, half));
const secondMap = makeMap(s.substring(half));
for (const [item, _] of firstMap) {
while (secondMap.has(item)) {
firstMap.set(item, firstMap.get(item) - 1);
secondMap.set(item, secondMap.get(item) - 1);
if (firstMap.get(item) === 0) {
break;
}
if (secondMap.get(item) === 0) {
break;
}
}
replacedCount += firstMap.get(item);
}
return replacedCount;
}