Python, stack solution
\ndef countOfAtoms(self, formula: str) -> str:\n\tstack = [defaultdict(int)]\n\tel = \'\'\n\tcnt = 0\n\tpopped = None\n\n\tfor ch in formula + \'#\':\n\t\tif ch
```\ndef countOfAtoms(self, formula: str) -> str:\n\tstack = [defaultdict(int)]\n\tel = \'\'\n\tcnt = 0\n\tpopped = None\n\n\tfor ch in formula + \'#\':\n\t\tif ch.isupper() or ch in \'()#\':  # time to flush\n\t\t\tif el:\n\t\t\t\tstack[-1][el] += cnt if cnt else 1\n\t\t\t\tel = \'\'\n\t\t\telif cnt or popped:\n\t\t\t\tfor elem, c in (popped or stack.pop()).items():\n\t\t\t\t\tstack[-1][elem] += c * max(cnt, 1)\n\t\t\t\tpopped = None\n\t\t\tcnt = 0\n\n\t\tif ch == \'(\':\n\t\t\tstack.append(defaultdict(int))\n\t\telif ch == \')\':\n\t\t\tpopped = stack.pop()\n\t\telif ch.isdigit():\n\t\t\tcnt = cnt * 10 + int(ch)\n\t\telse:\n\t\t\tel += ch\n\n\treturn \'\'.join([f\'{k}{c}\' if c > 1 else k for k, c in sorted(stack.pop().items())])\n```
['Python', 'Python3']