Number of Atoms

HardStringMathSortingStack

Description

Given a string formula representing a chemical formula, return the count of each atom in alphabetical order.

Examples

Input:formula = "H2O"
Output:"H2O"
Explanation:

Parse: H appears 2x, O appears 1x. Output alphabetically: H2O. No parentheses to expand.

Input:Ca(NO3)2
Output:"CaN2O6"
Explanation:

Ca:1, then (NO3)x2 = N:2, O:6. Alphabetically: CaN2O6.

Input:Al2(SO4)3
Output:"Al2O12S3"
Explanation:

Al:2, then (SO4)x3 = S:3, O:12. Alphabetically: Al2O12S3.

Constraints

  • 1 ≤ formula.length ≤ 1000
  • formula consists of letters, digits, '(', ')'.

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!