java.lang.Object
g1501_1600.s1541_minimum_insertions_to_balance_a_parentheses_string.Solution

public class Solution extends Object
1541 - Minimum Insertions to Balance a Parentheses String.<p>Medium</p> <p>Given a parentheses string <code>s</code> containing only the characters <code>'('</code> and <code>')'</code>. A parentheses string is <strong>balanced</strong> if:</p> <ul> <li>Any left parenthesis <code>'('</code> must have a corresponding two consecutive right parenthesis <code>'))'</code>.</li> <li>Left parenthesis <code>'('</code> must go before the corresponding two consecutive right parenthesis <code>'))'</code>.</li> </ul> <p>In other words, we treat <code>'('</code> as an opening parenthesis and <code>'))'</code> as a closing parenthesis.</p> <ul> <li>For example, <code>&quot;())&quot;</code>, <code>&quot;())(())))&quot;</code> and <code>&quot;(())())))&quot;</code> are balanced, <code>&quot;)()&quot;</code>, <code>&quot;()))&quot;</code> and <code>&quot;(()))&quot;</code> are not balanced.</li> </ul> <p>You can insert the characters <code>'('</code> and <code>')'</code> at any position of the string to balance it if needed.</p> <p>Return <em>the minimum number of insertions</em> needed to make <code>s</code> balanced.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> s = &ldquo;(()))&rdquo;</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong> The second &lsquo;(&rsquo; has two matching &lsquo;))&rsquo;, but the first &lsquo;(&rsquo; has only &lsquo;)&rsquo; matching. We need to to add one more &lsquo;)&rsquo; at the end of the string to be &ldquo;(())))&rdquo; which is balanced.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> s = &ldquo;())&rdquo;</p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong> The string is already balanced.</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> s = &ldquo;))())(&rdquo;</p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong> Add &lsquo;(&rsquo; to match the first &lsquo;))&rsquo;, Add &lsquo;))&rsquo; to match the last &lsquo;(&rsquo;.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= s.length <= 10<sup>5</sup></code></li> <li><code>s</code> consists of <code>'('</code> and <code>')'</code> only.</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • minInsertions

      public int minInsertions(String s)