1 题目
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 as
AB
(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
Note:
S.length <= 1000
S
only consists of'('
and')'
characters.
2 尝试解
2.1 分析
给定一串由"(",")"组成的字符串,但是括号的组合不一定有效。问至少要添加多少个"("或")"才能使得该字符串是有效的括号组合。
用left记录左括号的个数,result记录需要添加的括号个数。
如果遇到右括号,且左括号有剩余,则右括号与最近的一个左括号配对,left--;如果左括号没有剩余,则需要添加一个左括号。
如果遇到左括号,则left++。最后左括号有剩余,则需要给他们配上相同数目的右括号,result+=left。
2.2 代码
class Solution {
public:
int minAddToMakeValid(string S) {
int result = 0;
int left = 0;
for(auto letter : S){
if(letter == '(')
left++;
else{
if(left > 0) left--;
else result += 1;
}
}
result += left;
return result;
}
};
3 标准解
class Solution {
public:
int minAddToMakeValid(string S) {
int left = 0, right = 0;
for (char c : S)
if (c == '(')
right++;
else if (right > 0)
right--;
else
left++;
return left + right;
}
};