|
| 1 | +<h2><a href="https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced">1963. Minimum Number of Swaps to Make the String Balanced</a></h2><h3>Medium</h3><hr><p>You are given a <strong>0-indexed</strong> string <code>s</code> of <strong>even</strong> length <code>n</code>. The string consists of <strong>exactly</strong> <code>n / 2</code> opening brackets <code>'['</code> and <code>n / 2</code> closing brackets <code>']'</code>.</p> |
| 2 | + |
| 3 | +<p>A string is called <strong>balanced</strong> if and only if:</p> |
| 4 | + |
| 5 | +<ul> |
| 6 | + <li>It is the empty string, or</li> |
| 7 | + <li>It can be written as <code>AB</code>, where both <code>A</code> and <code>B</code> are <strong>balanced</strong> strings, or</li> |
| 8 | + <li>It can be written as <code>[C]</code>, where <code>C</code> is a <strong>balanced</strong> string.</li> |
| 9 | +</ul> |
| 10 | + |
| 11 | +<p>You may swap the brackets at <strong>any</strong> two indices <strong>any</strong> number of times.</p> |
| 12 | + |
| 13 | +<p>Return <em>the <strong>minimum</strong> number of swaps to make </em><code>s</code> <em><strong>balanced</strong></em>.</p> |
| 14 | + |
| 15 | +<p> </p> |
| 16 | +<p><strong class="example">Example 1:</strong></p> |
| 17 | + |
| 18 | +<pre> |
| 19 | +<strong>Input:</strong> s = "][][" |
| 20 | +<strong>Output:</strong> 1 |
| 21 | +<strong>Explanation:</strong> You can make the string balanced by swapping index 0 with index 3. |
| 22 | +The resulting string is "[[]]". |
| 23 | +</pre> |
| 24 | + |
| 25 | +<p><strong class="example">Example 2:</strong></p> |
| 26 | + |
| 27 | +<pre> |
| 28 | +<strong>Input:</strong> s = "]]][[[" |
| 29 | +<strong>Output:</strong> 2 |
| 30 | +<strong>Explanation:</strong> You can do the following to make the string balanced: |
| 31 | +- Swap index 0 with index 4. s = "[]][][". |
| 32 | +- Swap index 1 with index 5. s = "[[][]]". |
| 33 | +The resulting string is "[[][]]". |
| 34 | +</pre> |
| 35 | + |
| 36 | +<p><strong class="example">Example 3:</strong></p> |
| 37 | + |
| 38 | +<pre> |
| 39 | +<strong>Input:</strong> s = "[]" |
| 40 | +<strong>Output:</strong> 0 |
| 41 | +<strong>Explanation:</strong> The string is already balanced. |
| 42 | +</pre> |
| 43 | + |
| 44 | +<p> </p> |
| 45 | +<p><strong>Constraints:</strong></p> |
| 46 | + |
| 47 | +<ul> |
| 48 | + <li><code>n == s.length</code></li> |
| 49 | + <li><code>2 <= n <= 10<sup>6</sup></code></li> |
| 50 | + <li><code>n</code> is even.</li> |
| 51 | + <li><code>s[i]</code> is either <code>'[' </code>or <code>']'</code>.</li> |
| 52 | + <li>The number of opening brackets <code>'['</code> equals <code>n / 2</code>, and the number of closing brackets <code>']'</code> equals <code>n / 2</code>.</li> |
| 53 | +</ul> |
0 commit comments