Python Commented in Detail
\nclass Solution:\n    def countOfAtoms(self, formula: str) -> str:\n        i, n = 0, len(formula)\n        # Initialize a counter to keep track of the atoms\n
```\nclass Solution:\n    def countOfAtoms(self, formula: str) -> str:\n        i, n = 0, len(formula)\n        # Initialize a counter to keep track of the atoms\n        count = Counter()\n        stack = [count]\n\n        # Loop through the formula\n        while i < n:\n            # \'(\' indicates the start of a new formula\n            if formula[i] == \'(\':\n                i += 1\n                # Initialize a new counter for the new formula\n                count = Counter()\n                # Add the new counter to the stack\n                stack.append(count)\n            # \')\' indicates the end of a formula\n            elif formula[i] == \')\':\n                i += 1\n                # Find the end of the count that follows the \')\'\n                end = i\n                while i < n and formula[i].isdigit():\n                    i += 1\n                # Get the count, default to 1 if no count is provided\n                mult = int(formula[end:i] or 1)\n                top = stack.pop()\n                # Add the count of each atom in the popped counter to the top counter in the stack\n                for name, v in top.items():\n                    stack[-1][name] += v * mult\n                # Update the current counter to the top counter in the stack\n                count = stack[-1]\n            else:\n                # If the current character is not \'(\' or \')\', it\'s an atom\n                # Find the end of the atom name\n                start = i\n                i += 1\n                while i < n and formula[i].islower():\n                    i += 1\n                # Get the atom name\n                name = formula[start:i]\n                # Find the end of the count that follows the atom name\n                start = i\n                while i < n and formula[i].isdigit():\n                    i += 1\n                # Get the count, default to 1 if no count is provided\n                mult = int(formula[start:i] or 1)\n                # Add the count of the atom to the top counter in the stack\n                stack[-1][name] += mult\n\n        # Return the count of all atoms in the format specified in the problem\n        return "".join(name + (str(count[name]) if count[name] > 1 else \'\') for name in sorted(count))\n```
['String', 'Stack', 'Sorting', 'Python3']