Python: with stack and dict at O( nlog) solution
Intuition:\n1. Like a math problem, can be multiplied to get the overall count of a nested element if we read it from the end.\n2. Recursion/stack is required s
Intuition:\n1. Like a math problem, can be multiplied to get the overall count of a nested element if we read it from the end.\n2. Recursion/stack is required since it\'s nested \n3. keeping count can be quickly done with dict/hashmap\n\n```\nclass Solution(object):\n    def countOfAtoms(self, formula):\n        """\n        :type formula: str\n        :rtype: str\n        """\n        stack = [1] #\n        i = len(formula) - 1\n        nums_str = ""\n        num = 1\n        element = \'\'\n        atom_count = {}\n        while i >= 0:\n            \n            while \'0\' <= formula[i] <= \'9\':\n                nums_str = formula[i] + nums_str\n                i -= 1\n            \n            if nums_str != "":\n                num = int(nums_str)\n            \n            if formula[i] == ")":\n                stack.append(stack[-1]*num)\n            elif \'a\' <= formula[i] <= \'z\' or \'A\' <= formula[i] <= \'Z\':\n                while \'a\' <= formula[i] <= \'z\':\n                    element = formula[i] + element\n                    i -=1\n                element = formula[i] + element\n                if element in atom_count:\n                    atom_count[element] += num*stack[-1]\n                else:\n                    atom_count[element] = num*stack[-1]\n            else: # if (\n                stack.pop()\n            nums_str = ""\n            num = 1\n            element = \'\'            \n            i -= 1\n\n        outputs = [ "{}{}".format(k,v) if v > 1 else k for k,v in atom_count.items()]\n        outputs.sort()\n        str_output = "".join(outputs)\n        return str_output\n                \n```
[]