921. Minimum Add to Make Parentheses Valid(python+cpp)
阿新 • • 發佈:2018-11-09
題目:
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;
}
};
總結: