Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1a7ee3d

Browse files
Daily Solutions With JS
1 parent 0fe6b93 commit 1a7ee3d

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

‎Hard/726. Number of Atoms.js‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
var countOfAtoms = function(formula) {
2+
let stack = [];
3+
let cur = {};
4+
let i = 0;
5+
while (i < formula.length) {
6+
if (formula[i] === '(') {
7+
stack.push(cur);
8+
cur = {};
9+
i++;
10+
} else if (formula[i] === ')') {
11+
const [mult, newI] = readNextDigit(++i);
12+
i = newI;
13+
Object.keys(cur).forEach(key => cur[key] *= mult);
14+
const last = stack[stack.length - 1];
15+
// merge
16+
Object.keys(last).forEach(key => last[key] = last[key] + (cur[key] ?? 0));
17+
Object.keys(cur).forEach(key => {
18+
if (last[key] === undefined) {
19+
last[key] = cur[key];
20+
}
21+
});
22+
cur = stack.pop();
23+
} else {
24+
const [ele, newI] = readNextElement(i);
25+
i = newI;
26+
const [c, nI] = readNextDigit(i);
27+
i = nI;
28+
cur[ele] = (cur[ele] ?? 0) + c;
29+
}
30+
}
31+
32+
return Object.entries(cur).sort((a,b) => a[0].localeCompare(b[0])).reduce((r, [key, val]) => r += `${key}${val === 1 ? '' : val}`, "");
33+
34+
35+
function readNextElement(i) {
36+
if (!formula[i].match(/[A-Z]/)) return null;
37+
let res = formula[i++];
38+
while (formula[i]?.match(/[a-z]/)) {
39+
res += formula[i++];
40+
}
41+
42+
return [res, i];
43+
}
44+
45+
function readNextDigit(i) {
46+
if (!formula[i]?.match(/[0-9]/)) return [1, i];
47+
let res = 0;
48+
while (formula[i]?.match(/[0-9]/)) {
49+
res = res * 10 + +formula[i++];
50+
}
51+
52+
return [res, i];
53+
}
54+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /