题目:
Given a string
S
of'('
and')'
parentheses, we add the minimum number of parentheses ('('
or ’)',
and in any positions ) so that the resulting parentheses string is valid.
Formally, a parentheses string is valid if and only if:
It is the empty string, or
It can be written asAB
(A
concatenated withB
), whereA
andB
are valid strings, or
It can be written as(A)
,whereA
is a valid string.
Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.
Example 1:Input: "())" Output: 1
Example 2:
Input: "(((" Output: 3
Example 3:
Input: "()" Output: 0
Example 4:
Input: "()))((" Output: 4
解释:
需要补充几个括号使得括号组成的string变为valid,看到括号的题目就想用stack做怎么办。用传统的括号匹配问题,需要用一个count变量记录没有匹配的)
的个数,最后返回stack的长度+count即可,其中stack的长度表示没有匹配的(
的个数。
python代码:
class Solution(object):
def minAddToMakeValid(self, S):
"""
:type S: str
:rtype: int
"""
stack=[]
count=0
for letter in S:
if letter=='(':
stack.append(letter)
else:
if stack:
stack.pop(-1)
else:
count+=1
return len(stack)+count
实际上不用栈,也用另一个计数器记录(
的个数即可,其实也是栈的思想。
python代码:
class Solution(object):
def minAddToMakeValid(self, S):
"""
:type S: str
:rtype: int
"""
left,right=0,0
for letter in S :
if letter=='(':
left+=1
else:
if left>0:
left-=1
else:
right+=1
return left+right
c++代码:
class Solution {
public:
int minAddToMakeValid(string S) {
int left=0,right=0;
for(auto letter:S)
{
if (letter=='(')
left++;
else
{
if(left)
left--;
else
right++;
}
}
return left+right;
}
};
总结: