Python3 use stack with brief explanation comments
\nfrom collections import defaultdict\n\ndef isLower(ch):\n    return ord(\'a\') <= ord(ch) and ord(ch) <= ord(\'z\')\n\ndef toStr(num):\n    if num == 1:\n    
```\nfrom collections import defaultdict\n\ndef isLower(ch):\n    return ord(\'a\') <= ord(ch) and ord(ch) <= ord(\'z\')\n\ndef toStr(num):\n    if num == 1:\n        return ""\n    else:\n        return str(num)   \n    \ndef getAtom(i, s): # get atom and next index\n    N = len(s)\n    ret = s[i]\n    i+=1\n    while i < N and s[i].isalpha() and isLower(s[i]):\n        ret += s[i]\n        i+=1\n    return ret, i\n\ndef getNumber(i, s): # get number and next index\n    N = len(s)\n    ret = ""\n    while i < N and s[i].isdigit():\n        ret += s[i]\n        i += 1\n    return int(ret), i\n\nclass Solution:    \n    def countOfAtoms(self, s: str) -> str:\n        # use stack\n        # atom + number : stack last {\'atom\': += number }\n        # atom + not number: stack last {\'atom\': +=1 }\n        # \')\' + number : stack last {\'atom\': *= number } -> add all to the previous stack and pop \n\t\t# \') + not number: add all stack last to the previous stack and pop\n        # \'(\':  add {} to stack  \n\n        N = len(s)                                        \n\n        stack = [defaultdict(int)] # stack[0] is the answer\n        i = 0\n        while i < N:\n            ch = s[i]\n            if ch == \'(\':\n                stack.append(defaultdict(int))\n                i += 1                \n            elif ch == \')\':\n                num = 1\n                if i+1 < N and s[i+1].isdigit(): # ex: ...H20)32 you should get the number "32"\n                    num, i = getNumber(i+1, s)\n                else:\n                    i += 1    \n                atoms = stack.pop()\n                for atom in atoms.keys():\n                    stack[-1][atom] += num * atoms[atom]                \n            else: # ch is alphabet\n                atom, i = getAtom(i, s)\n                if i < N and s[i].isdigit():\n                    num, i = getNumber(i, s)\n                    stack[-1][atom] += num\n                else:\n                    stack[-1][atom] += 1\n                    \n        ans = sorted(list(stack[0].items()), key=lambda x:x[0])   \n        \n        return \'\'.join([atom+toStr(num) for atom, num in ans])\n\n```
[]