Atoms in a Hydrate Formula
formula describes a chemical compound. Count the atoms of each element in it:
- An element is an uppercase letter, optionally followed by one lowercase letter, like
H,CuorCl. - A number after an element multiplies it:
O2is twoO. No number means one. - A group in round brackets
(...)or square brackets[...]may be followed by a number that multiplies everything inside it. Groups can be nested. - A
.splits the formula into parts, and a part may start with a number that multiplies the whole part:CuSO4.5H2OisCuSO4plus fiveH2O.
Return every element once, in alphabetical order (plain string order, so C comes before Ca), each followed by its total count when that count is more than 1. For CuSO4.5H2O the answer is "CuH10O9S".
Example 1
formula "CuSO4.5H2O"
returns "CuH10O9S"
CuSO4 gives one Cu, one S and 4 O, and five H2O give 10 H and 5 more O.
Example 2
formula "[Co(NH3)6]Cl3"
returns "Cl3CoH18N6"
(NH3)6 gives 6 N and 18 H. Add one Co and 3 Cl, and sort the names: Cl, Co, H, N.
Constraints
1 <= len(formula) <= 60- every number in
formulais from2to99 - brackets are balanced and properly nested, and every group and every part holds at least one element
- every total count is below
10^9
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.