Python [stack + hashmap] solution with algorithm explanation. 28 ms
Algorithm:\n1) We are starting from the last element.\n2) When we find on our way any number, lowercase char, or parentheses, we do some additions and then cont
Algorithm:\n1) We are starting from the last element.\n2) When we find on our way any *number*, *lowercase char*, or *parentheses*, we do some additions and then `continue`\n\u2014 If it was a ***number*** we want to know how much digits it has\n\u2014 If it was a ***lowercase char*** we want to store it in variable `lower` and append it to the `key = formula[i] + lower` on the next cycle\n\u2014 If it was a ***closing parenthesis*** we want to store it\'s multiplier in our stack `m.append(digit * m[-1])` \n\u2014 If it was an ***opening parenthesis*** we should remove the last multiplier `m.pop()`\n3) After that we add the `key = element` and `value = m[-1] * int(digit or 1)` to our dictionary (hashmap). \n\n\n```\nclass Solution:\n    def countOfAtoms(self, formula: str) -> str:\n        formula = formula + \' \'\n        dict = {}\n        m = [1]\n        digit = \'\' \n        lower = \'\'\n        \n        for i in range(len(formula)-2, -1, -1):\n            element = formula[i] + lower\n            if element.isdigit():\n                digit = element + digit\n                continue\n            elif element.islower():\n                lower = element + lower\n                continue\n            elif element == \')\':\n                m.append(m[-1] * int(digit))\n                digit = \'\'\n                continue\n            elif element == \'(\':\n                m.pop()\n                continue\n            dict[element] = dict.get(element, 0) + m[-1]*int(digit or 1)\n            digit = \'\'\n            lower = \'\'\n\n        output = \'\'\n        for key, value in sorted(dict.items()):\n            if value == 1:\n                value = \'\'\n            output = output + key + str(value)\n        return output\n```\nRuntime: 28 ms, faster than 98.88% of Python3 online submissions for Number of Atoms.\nMemory Usage: 13.9 MB, less than 50.00% of Python3 online submissions for Number of Atoms.
['Python']