Python3 Solution
\n\nclass Solution:\n    def countOfAtoms(self, formula: str) -> str:\n        n=len(formula)\n        stack=[]\n        count=defaultdict(lambda:0)\n        c=
\n```\nclass Solution:\n    def countOfAtoms(self, formula: str) -> str:\n        n=len(formula)\n        stack=[]\n        count=defaultdict(lambda:0)\n        c=""\n        s=""\n        for i in reversed(formula):\n            if i.isdigit():\n                c=i+c\n            elif i==\')\':\n                if c:\n                    if not stack:\n                        stack.append(int(c))\n                    else:\n                        top=stack[-1]\n                        stack.append(top*int(c))\n                    c=""\n            elif i=="(":\n                if stack:\n                    stack.pop()\n            elif i.islower():\n                s=i+s\n            else:\n                s=i+s\n                if c:\n                    if stack:\n                        count[s]+=int(c)*stack[-1]\n                    else:\n                        count[s]+=int(c)\n                    c=""\n                                                \n                else:\n                    if stack:\n                        count[s]+=stack[-1]\n                    else:\n                        count[s]+=1\n                s=""\n        ans=""\n        for i in sorted(count):\n            if count[i]>1:\n                ans+=i+str(count[i])\n            else:\n                ans+=i\n        return ans            \n```
['Python', 'Python3']