Algorithm


Problem Name: 726. Number of Atoms

Problem Link: https://leetcode.com/problems/number-of-atoms/

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

The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.

One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.

  • For example, "H2O" and "H2O2" are possible, but "H1O2" is impossible.

Two formulas are concatenated together to produce another formula.

  • For example, "H2O2He3Mg4" is also a formula.

A formula placed in parentheses, and a count (optionally added) is also a formula.

  • For example, "(H2O2)" and "(H2O2)3" are formulas.

Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.

The test cases are generated so that all the values in the output 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}.

 

Constraints:

  • 1 <= formula.length <= 1000
  • formula consists of English letters, digits, '(', and ')'.
  • formula is always valid.

 

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


function countOfAtoms(formula) {
  let [dic, coeff, stack, elem, cnt, j, res] = [{}, 1, [], '', 0, 0, '']
  for (let i = formula.length - 1; i >= 0; i--) {
    if (!isNaN(formula[i] * 1)) {
      ;(cnt += Number(formula[i]) * 10 ** j), (j += 1)
    } else if (formula[i] == ')') {
      stack.push(cnt), (coeff *= cnt), (j = cnt = 0)
    } else if (formula[i] == '(') {
      ;(coeff = Math.floor(coeff / stack.pop())), (j = cnt = 0)
    } else if (formula[i] == formula[i].toUpperCase()) {
      elem += formula[i]
      elem = elem
        .split('')
        .reverse()
        .join('')
      dic[elem] = dic[elem] || 0
      dic[elem] += (cnt || 1) * coeff
      ;(elem = ''), (j = cnt = 0)
    } else {
      elem += formula[i]
    }
  }
  Object.keys(dic)
    .sort()
    .forEach(function(c) {
      res += dic[c] > 1 ? c + String(dic[c]) : c
    })
  return res
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
formula = "H2O"

Output

x
+
cmd
"H2O"

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def countOfAtoms(self, formula):
        dic, coeff, stack, elem, cnt, i = collections.defaultdict(int), 1, [], "", 0, 0  
        for c in formula[::-1]:
            if c.isdigit():
                cnt += int(c) * (10 ** i)
                i += 1
            elif c == ")":
                stack.append(cnt)
                coeff *= cnt
                i = cnt = 0
            elif c == "(":
                coeff //= stack.pop()
                i = cnt = 0
            elif c.isupper():
                elem += c
                dic[elem[::-1]] += (cnt or 1) * coeff
                elem = ""
                i = cnt = 0
            elif c.islower():
                elem += c
        return "".join(k + str(v > 1 and v or "") for k, v in sorted(dic.items()))
Copy The Code & Try With Live Editor

Input

x
+
cmd
formula = "H2O"

Output

x
+
cmd
"H2O"

#3 Code Example with C# Programming

Code - C# Programming


using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LeetCode
{
    public class _0726_NumberOfAtoms
    {
        public string CountOfAtoms(string formula)
        {
            var map = Parser(formula, 0, formula.Length);

            var sb = new StringBuilder();
            foreach (var key in map.Keys.OrderBy(k => k))
            {
                sb.Append(key);
                if (map[key] > 1)
                    sb.Append(map[key]);
            }

            return sb.ToString();
        }

        private IDictionary < string, int> Parser(string formula, int start, int end)
        {
            var results = new Dictionary();

            var count = 0;
            var atom = string.Empty;
            for (int i = start; i  <  end; i++)
            {
                var ch = formula[i];
                if (char.IsDigit(ch))
                    count = count * 10 + ch - '0';
                else if (char.IsLower(ch))
                    atom += ch;
                else if (char.IsUpper(ch))
                {
                    if (atom != string.Empty)
                    {
                        if (results.ContainsKey(atom))
                            results[atom] += count == 0 ? 1 : count;
                        else
                            results[atom] = count == 0 ? 1 : count;
                    }
                    atom = ch.ToString();
                    count = 0;
                }
                else if (ch == '(')
                {
                    if (atom != string.Empty)
                    {
                        if (results.ContainsKey(atom))
                            results[atom] += count == 0 ? 1 : count;
                        else
                            results[atom] = count == 0 ? 1 : count;
                    }
                    atom = string.Empty;
                    count = 0;

                    var balance = 1;
                    var j = i;
                    while (balance != 0)
                    {
                        j++;
                        if (formula[j] == '(')
                            balance++;
                        else if (formula[j] == ')')
                            balance--;
                    }
                    var map = Parser(formula, i + 1, j);
                    i = j;
                    while (++i  <  end && char.IsDigit(formula[i]))
                        count = count * 10 + formula[i] - '0';
                    i--;

                    foreach (var key in map.Keys)
                    {
                        if (results.ContainsKey(key))
                            results[key] += map[key] * count;
                        else
                            results[key] = map[key] * count;
                    }
                    count = 0;
                }
            }

            if (atom != string.Empty)
            {
                if (results.ContainsKey(atom))
                    results[atom] += count == 0 ? 1 : count;
                else
                    results[atom] = count == 0 ? 1 : count;
            }

            return results;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
formula = "Mg(OH)2"

Output

x
+
cmd
"H2MgO2"
Advertisements

Demonstration


Previous
#725 Leetcode Split Linked List in Parts Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#728 Leetcode Self Dividing Numbers Solution in C, C++, Java, JavaScript, Python, C# Leetcode