diff options
author | Jack Sangdahl <[email protected]> | 2024-10-07 18:10:00 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2024-10-07 18:10:00 -0600 |
commit | 2392e12d18162e1ad9083f4ec9f2498238302795 (patch) | |
tree | 2e4ecc59aead4b1c0c16f311c1e69a52d13b5323 /min_num_swap_string_balance.py | |
parent | b9c16a156eff8ebe6627a0869fdd6d360aec9bc5 (diff) | |
download | leetcode-2392e12d18162e1ad9083f4ec9f2498238302795.tar.gz leetcode-2392e12d18162e1ad9083f4ec9f2498238302795.zip |
1963. minimum number of swaps to make the string balanced
Diffstat (limited to 'min_num_swap_string_balance.py')
-rw-r--r-- | min_num_swap_string_balance.py | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/min_num_swap_string_balance.py b/min_num_swap_string_balance.py new file mode 100644 index 0000000..d7114f8 --- /dev/null +++ b/min_num_swap_string_balance.py @@ -0,0 +1,33 @@ +# 1963. Minimum Number of Swaps to Make the String Balanced + +""" +you are given a 0-indexed string 's' of even length 'n'. the string consists +of exactly 'n / 2' opening and closing square brackets. a string is called +balanced if and only if it is empty string, it can be written as 'AB' where +both 'A' and 'B' are balanced strings, or it can be written as '[C]' where +'C' is a balanced string. you may swap the brackets at any two indices any +number of times. return the minimum number of swaps to make 's' balanced +""" + + +class Solution(object): + def minSwaps(self, s): + """ + :type s: str + :rtype: int + """ + bal, ans = 0, 0 + for c in s: + if c == "[": + bal += 1 + else: + bal -= 1 + ans = min(ans, bal) + return (-ans + 1) // 2 + + +if __name__ == "__main__": + obj = Solution() + print(obj.minSwaps(s="][][")) + print(obj.minSwaps(s="]]][[[")) + print(obj.minSwaps(s="[]")) |