Python // 20 lines very readable, simplest and shortest solution // 36 ms // beats 100 %
Just check every character from right to left\n if character is digit, add to current numeric counter\n if character is ")", multiply big coefficient and add nu
* Just check every character from right to left\n* if character is digit, add to current numeric counter\n* if character is ")", multiply big coefficient and add numeric counter to stack\n* if character is "(", we won\'t multiply next elements with last numeric counter so remove last counter and divide big coefficient by last counter\n* if character is alphabetic and uppercase, we have to add element and its coefficient to dictionary\n* if character is alphabetic and lowercase, just add character to current element.\n* return string by joining sorted key and value pairs in dictionary\n```\nclass Solution:\n    def countOfAtoms(self, formula):\n        dic, coeff, stack, elem, cnt, i = collections.defaultdict(int), 1, [], "", 0, 0  \n        for c in formula[::-1]:\n            if c.isdigit():\n                cnt += int(c) * (10 ** i)\n                i += 1\n            elif c == ")":\n                stack.append(cnt)\n                coeff *= cnt\n                i = cnt = 0\n            elif c == "(":\n                coeff //= stack.pop()\n                i = cnt = 0\n            elif c.isupper():\n                elem += c\n                dic[elem[::-1]] += (cnt or 1) * coeff\n                elem = ""\n                i = cnt = 0\n            elif c.islower():\n                elem += c\n        return "".join(k + str(v > 1 and v or "") for k, v in sorted(dic.items()))\n```
[]