October 9Medium
Minimum insertions to balance a parentheses string
- String
- Stack
- Greedy
- Bracket Sequences
Problem
Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:
- Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'. - Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.
In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.
- For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced.
You can insert the characters '(' and ')' at any position of the string to balance it if needed.
Return the minimum number of insertions needed to make s balanced.
Solution
class Solution:
def minInsertions(self, s: str) -> int:
ans, opened, i = 0, 0, 0
while i < len(s):
if s[i] == "(":
opened += 1
else:
if opened:
opened -= 1
else:
ans += 1
if i == len(s) - 1 or s[i+1] != ")":
ans += 1
else:
i += 1
i += 1
return ans + 2*opened