A chemical formula string represents different elements and their quantities.
Each element begins with a capital letter and may include lowercase letters after it.
A number following an element indicates how many times that element appears—if no number is present, the quantity is 1.
Formulas may contain:
Simple sequences, like "NaCl"
Repeated groups, like "H2O" or "C6H12O6"
Nested parentheses, e.g. "(OH)2" or "K4(ON(SO3)2)2"
Your task is to compute how many times each atom appears in the whole formula.
Finally, return a string that lists all atom names in sorted order, and append their counts (except when the count is 1).
All final quantities will fit in a 32-bit integer.
Input: formula = "C6H5OH"
Output: "C6H6O"
Input: formula = "Fe2(SO4)3"
Output: "Fe2O12S3"
Explanation:
Fe appears 2 times SO₄ is repeated 3 times → O: 4×3 = 12, S:1×3 = 3
Input: formula = "Al2(OH)5Mg3"
Output: "Al2H5Mg3O5"
Explanation:
Counts: Al:2, O:5, H:5, Mg:3.
Accepted:
Submission: