-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path726. Number of Atoms.js
54 lines (48 loc) · 1.6 KB
/
726. Number of Atoms.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
var countOfAtoms = function(formula) {
let stack = [];
let cur = {};
let i = 0;
while (i < formula.length) {
if (formula[i] === '(') {
stack.push(cur);
cur = {};
i++;
} else if (formula[i] === ')') {
const [mult, newI] = readNextDigit(++i);
i = newI;
Object.keys(cur).forEach(key => cur[key] *= mult);
const last = stack[stack.length - 1];
// merge
Object.keys(last).forEach(key => last[key] = last[key] + (cur[key] ?? 0));
Object.keys(cur).forEach(key => {
if (last[key] === undefined) {
last[key] = cur[key];
}
});
cur = stack.pop();
} else {
const [ele, newI] = readNextElement(i);
i = newI;
const [c, nI] = readNextDigit(i);
i = nI;
cur[ele] = (cur[ele] ?? 0) + c;
}
}
return Object.entries(cur).sort((a,b) => a[0].localeCompare(b[0])).reduce((r, [key, val]) => r += `${key}${val === 1 ? '' : val}`, "");
function readNextElement(i) {
if (!formula[i].match(/[A-Z]/)) return null;
let res = formula[i++];
while (formula[i]?.match(/[a-z]/)) {
res += formula[i++];
}
return [res, i];
}
function readNextDigit(i) {
if (!formula[i]?.match(/[0-9]/)) return [1, i];
let res = 0;
while (formula[i]?.match(/[0-9]/)) {
res = res * 10 + +formula[i++];
}
return [res, i];
}
};