1541. Minimum Insertions to Balance a Parentheses String (Medium) - TengnanYao/daily_leetcode GitHub Wiki
class Solution(object):
def minInsertions(self, s):
"""
:type s: str
:rtype: int
"""
result = l = r = 0
for c in s:
if c == "(":
if r == 1:
result += 1
if l > 0:
l -= 1
else:
result += 1
r = 0
l += 1
else:
r += 1
if r == 2:
if l > 0:
l -= 1
else:
result += 1
r = 0
if l < r:
return result + 2
else:
return result + 2 * l - r