bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 726. Number of Atoms

726. Number of Atoms

Leetcode Solutions

Approach #: Stack [Accepted]

  1. Initialize a stack with one empty count map.
  2. Initialize an index variable i to 0.
  3. While i is less than the length of the formula: a. If the current character is '(', push a new empty count map onto the stack. b. If the current character is an uppercase letter, parse the element name and count. Update the count in the current scope. c. If the current character is ')', pop the top count map off the stack, multiply its counts by the number following the ')', and add these counts to the next count map on the stack.
  4. After processing the entire formula, pop the remaining count map off the stack. This is the total count of each element.
  5. Sort the elements by name and format the result.
UML Thumbnail

Approach #: Recursion [Accepted]

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...