Javascript - Stack and Map
Code\n\n/**\n * @param {string} formula\n * @return {string}\n */\nvar countOfAtoms = function (formula) {\n  let map = {};\n  const stack = [];\n  const n = fo
# Code\n```\n/**\n * @param {string} formula\n * @return {string}\n */\nvar countOfAtoms = function (formula) {\n  let map = {};\n  const stack = [];\n  const n = formula.length;\n\n  let i = 0;\n  while (i < n) {\n    const char = formula[i++];\n    if (char === \'(\') {\n      stack.push({ ...map });\n      map = {};\n    } else if (char === \')\') {\n      let val = 0;\n      while (i < n && formula[i] >= \'0\' && formula[i] <= \'9\') {\n        val = val * 10 + +formula[i++];\n      }\n      if (val === 0) val = 1;\n\n      const prevMap = stack.pop();\n      for (const key of Object.keys(map)) {\n        map[key] = map[key] * val;\n        prevMap[key] = (prevMap[key] || 0) + map[key];\n      }\n      map = prevMap;\n    } else {\n      const start = i - 1;\n      while (i < n && formula[i] >= \'a\' && formula[i] <= \'z\') {\n        i++;\n      }\n      const name = formula.slice(start, i);\n\n      let val = 0;\n      while (i < n && formula[i] >= \'0\' && formula[i] <= \'9\') {\n        val = val * 10 + +formula[i++];\n      }\n      if (val === 0) val = 1;\n      map[name] = (map[name] || 0) + val;\n    }\n  }\n\n  let ans = \'\';\n  const keys = Object.keys(map).sort();\n  for (const key of keys) {\n    ans += `${key}${map[key] === 1 ? \'\' : map[key]}`;\n  }\n  return ans;\n};\n\n```
['Stack', 'JavaScript']