Class Solution

java.lang.Object
g0701_0800.s0726_number_of_atoms.Solution

public class Solution extends Object
726 - Number of Atoms.<p>Hard</p> <p>Given a string <code>formula</code> representing a chemical formula, return <em>the count of each atom</em>.</p> <p>The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.</p> <p>One or more digits representing that element&rsquo;s count may follow if the count is greater than <code>1</code>. If the count is <code>1</code>, no digits will follow.</p> <ul> <li>For example, <code>&quot;H2O&quot;</code> and <code>&quot;H2O2&quot;</code> are possible, but <code>&quot;H1O2&quot;</code> is impossible.</li> </ul> <p>Two formulas are concatenated together to produce another formula.</p> <ul> <li>For example, <code>&quot;H2O2He3Mg4&quot;</code> is also a formula.</li> </ul> <p>A formula placed in parentheses, and a count (optionally added) is also a formula.</p> <ul> <li>For example, <code>&quot;(H2O2)&quot;</code> and <code>&quot;(H2O2)3&quot;</code> are formulas.</li> </ul> <p>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 <code>1</code>), followed by the second name (in sorted order), followed by its count (if that count is more than <code>1</code>), and so on.</p> <p>The test cases are generated so that all the values in the output fit in a <strong>32-bit</strong> integer.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> formula = &ldquo;H2O&rdquo;</p> <p><strong>Output:</strong> &ldquo;H2O&rdquo;</p> <p><strong>Explanation:</strong> The count of elements are {&lsquo;H&rsquo;: 2, &lsquo;O&rsquo;: 1}.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> formula = &ldquo;Mg(OH)2&rdquo;</p> <p><strong>Output:</strong> &ldquo;H2MgO2&rdquo;</p> <p><strong>Explanation:</strong> The count of elements are {&lsquo;H&rsquo;: 2, &lsquo;Mg&rsquo;: 1, &lsquo;O&rsquo;: 2}.</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> formula = &ldquo;K4(ON(SO3)2)2&rdquo;</p> <p><strong>Output:</strong> &ldquo;K4N2O14S4&rdquo;</p> <p><strong>Explanation:</strong> The count of elements are {&lsquo;K&rsquo;: 4, &lsquo;N&rsquo;: 2, &lsquo;O&rsquo;: 14, &lsquo;S&rsquo;: 4}.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= formula.length <= 1000</code></li> <li><code>formula</code> consists of English letters, digits, <code>'('</code>, and <code>')'</code>.</li> <li><code>formula</code> is always valid.</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • countOfAtoms

      public String countOfAtoms(String formula)