#726

Number of Atoms

expert · 1100 · lc hard +32 · verified · 65.1% accepted · 1,972 likes · top 69%

Description

Parse a chemical formula string and return the atom counts as a formatted string. Element names begin with an uppercase letter followed by zero or more lowercase letters. An optional digit count follows when the count exceeds 1 (a count of 1 is never written). Formulas may be concatenated or wrapped in parentheses with a multiplier (e.g., "(H2O2)3").

Return a string listing each element in alphabetical order followed by its total count (omitting the count when it is 1). All counts fit in a 32-bit integer.

Example 1:

Input: formula = "H2O"
Output: "H2O"
Explanation: The count of elements are {'H': 2, 'O': 1}.

Example 2:

Input: formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.

Example 3:

Input: formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.

Code

1
2
3