题目:
给你一个括号字符串 s ,它只包含字符 '(' 和 ')' 。一个括号字符串被称为平衡的当它满足:
- 任何左括号
'('必须对应两个连续的右括号'))'。 - 左括号
'('必须在对应的连续两个右括号'))'之前。
比方说 "())", "())(())))" 和 "(())())))" 都是平衡的, ")()", "()))" 和 "(()))" 都是不平衡的。
你可以在任意位置插入字符 '(' 和 ')' 使字符串平衡。
请你返回让 s 平衡的最少插入次数。
算法:
方法一:贪心
突破点在第一个右括号,以它为考虑基准点
func minInsertions(s string) int {
leftCount := 0
ans := 0
for i := 0; i < len(s); {
if s[i] == '(' {
leftCount ++
i ++
} else {
if leftCount > 0 {
leftCount --
} else {
ans ++
}
if i + 1 < len(s) && s[i + 1] == ')' {
i = i + 2
} else {
ans ++
i ++
}
}
}
ans = ans + leftCount * 2
return ans
}