|
| 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