2
def countOfAtoms(self, formula: str) -> str:3
stack, elem, i = [{}], "", 05
while i < len(formula):6
# Extract the full element name7
if formula[i].isupper():9
while j < len(formula) and formula[j].islower():13
# If no digits follow the element, assign a count of 116
or not formula[i].isdigit()17
and not formula[i].islower()19
stack[-1][elem] = stack[-1].get(elem, 0) + 121
elif formula[i].isdigit():23
while j < len(formula) and formula[j].isdigit():25
count = int(formula[i:j])26
stack[-1][elem] = stack[-1].get(elem, 0) + count28
# Handle open parentheses by pushing a new dict29
elif formula[i] == "(":32
# Handle close parentheses by merging with the previous dict33
elif formula[i] == ")":36
while j < len(formula) and formula[j].isdigit():38
multiplier = int(formula[i:j] or 1)40
for elem, count in top.items():41
stack[-1][elem] = stack[-1].get(elem, 0) + count * multiplier44
# Convert the result to the desired format45
atoms = sorted(stack[0].items())47
[atom + (str(count) if count > 1 else "") for atom, count in atoms]