Neat Python with Explanation - 35ms
The first regex ([A-Z]{1}[a-z]?|\\(|\\)|\\d+) splits up the input string into a few kinds of tokens for parsing: (1) An atom (2) A number (3) Open bracket (4) C
The first regex `([A-Z]{1}[a-z]?|\\(|\\)|\\d+)` splits up the input string into a few kinds of tokens for parsing: (1) An atom (2) A number (3) Open bracket (4) Closing bracket. These are the only tokens we need to do our parsing.\n\nAn input of `Mg(OH)2` will be tokenized into: `[\'Mg\', \'(\', \'O\', \'H\', \')\', \'2\']`.\nAn input of `K4(ON(SO3)2)2` will be tokenized into: `[\'K\', \'4\', \'(\', \'O\', \'N\', \'(\', \'S\', \'O\', \'3\', \')\', \'2\', \')\', \'2\']`.\n\nAs we iterate through the tokens, there are three cases that we need to handle:\n\n1. Open bracket - We push a new dictionary onto a stack to keep track of the atoms and its count in this current group\n2. Close bracket - The next token might be a number/count. Check whether if it is a count. If it is, multiply all the atoms at the top of the stack by the count and combine it with a dictionary below it in the stack.\n3. Normal atom - The next token might be a number/count. Check whether if it is a count. If it is, add that atom and its count to the top of the stack.\n\nCases 2 and 3 are very similar, so we can combine them.\n\nAt the end, sort the atoms alphabetically and format them nicely to be returned.\n\n**\uD83D\uDCAF Check out https://www.techinterviewhandbook.org for more tips and tricks by me to ace your coding interview \uD83D\uDCAF**\n\n```\nclass Solution(object):\n    def countOfAtoms(self, formula):\n        import re\n        from collections import defaultdict\n        tokens = list(filter(lambda c: c, re.split(\'([A-Z]{1}[a-z]?|\\(|\\)|\\d+)\', formula)))\n        stack, i = [defaultdict(int)], 0\n        while i < len(tokens):\n            token = tokens[i]\n            if token == \'(\':\n                stack.append(defaultdict(int))\n            else:\n                count = 1\n                # Check if next token is a number.\n                if i + 1 < len(tokens) and re.search(\'^\\d+$\', tokens[i + 1]):\n                    count, i = int(tokens[i + 1]), i + 1\n                atoms = stack.pop() if token == \')\' else { token: 1 }\n                # Combine counts of atoms.\n                for atom in atoms:\n                    stack[-1][atom] += atoms[atom] * count\n            i += 1\n        return \'\'.join([atom + (str(count) if count > 1 else \'\') for atom, count in sorted(stack[-1].items())])\n```
[]