1963. Minimum Number of Swaps to Make the String Balanced Medium

@problem@discussion
#Two Pointers#String#Stack#Greedy



1/**
2 * [1963] Minimum Number of Swaps to Make the String Balanced
3 *
4 * You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.
5 * A string is called balanced if and only if:
6 * 
7 * 	It is the empty string, or
8 * 	It can be written as AB, where both A and B are balanced strings, or
9 * 	It can be written as [C], where C is a balanced string.
10 * 
11 * You may swap the brackets at any two indices any number of times.
12 * Return the minimum number of swaps to make s balanced.
13 *  
14 * Example 1:
15 * 
16 * Input: s = "][]["
17 * Output: 1
18 * Explanation: You can make the string balanced by swapping index 0 with index 3.
19 * The resulting string is "[[]]".
20 * 
21 * Example 2:
22 * 
23 * Input: s = "]]][[["
24 * Output: 2
25 * Explanation: You can do the following to make the string balanced:
26 * - Swap index 0 with index 4. s = "[]][][".
27 * - Swap index 1 with index 5. s = "[[][]]".
28 * The resulting string is "[[][]]".
29 * 
30 * Example 3:
31 * 
32 * Input: s = "[]"
33 * Output: 0
34 * Explanation: The string is already balanced.
35 * 
36 *  
37 * Constraints:
38 * 
39 * 	n == s.length
40 * 	2 <= n <= 10^6
41 * 	n is even.
42 * 	s[i] is either '[' or ']'.
43 * 	The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.
44 * 
45 */
46pub struct Solution {}
47
48// problem: https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/
49// discuss: https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/discuss/?currentPage=1&orderBy=most_votes&query=
50
51// submission codes start here
52
53impl Solution {
54    pub fn min_swaps(s: String) -> i32 {
55        0
56    }
57}
58
59// submission codes end
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_1963() {
67    }
68}
69


Back
© 2025 bowen.ge All Rights Reserved.