使括号有效的最少添加
https://www.lintcode.com/problem/1721/description?utm_source=sc-libao-ql
描述
给定一个由 '(' 和 ')' 括号组成的字符串 S,我们需要添加最少的括号( '(' 或是 ')',可以在任何位置),以使得到的括号字符串有效。
从形式上讲,只有满足下面几点之一,括号字符串才是有效的:
它是一个空字符串,或者
它可以被写成
AB(A与B连接), 其中A和B都是有效字符串,或者它可以被写作
(A),其中A是有效字符串。
给定一个括号字符串,返回为使结果字符串有效而必须添加的最少括号数。
S.length <= 1000
S 只包含 '(' 和 ')' 字符。
样例
样例 1:
输入: "())"输出: 1样例 2:
输入: "((("输出: 3样例 3:
输入: "()"输出: 0样例 4:
输入: "()))(("输出: 4class Solution:
"""
@param s: the given string
@return: the minimum number of parentheses we must add
"""
def min_add_to_make_valid(self, s: str) -> int:
# Write your code here
l,r=0,0
for c in s:
if c == '(':
l += 1
elif c == ')':
if l > 0:
l-=1
else:
r += 1
return l+r
Last updated
Was this helpful?