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(Aconcatenated withB), whereAandBare valid strings, or - It can be written as
(A), whereAis 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 <= 1000Sonly consists of'('and')'characters.
题意:给出一个仅由"("和")"组成的字符串,求最少向字符串中加入多少个"(",")"字符,该字符串变得合法。合法是指由"("和")"组成的字符串满足以下条件:(1)为一个空串;(2)可以写成AB的形式,这里A、B都是合法的字符串;(3)可以写成(A)的形式,A是一个合法的字符串。
思路:从左向右遍历,记录左括号的数量。当遍历到右括号且前面有可用的左括号时,两者匹配抵消,否则要在前面增加左括号。最后剩余的左括号还要用右括号与其匹配。
class Solution{
public:
int minAddToMakeValid(string s){
int left=0,ans=0;
for(int i=0;i<s.length();i++){
if(s[i]=='(')
left++;
else if(s[i]==')'&&left>0)
left--;
else
ans++;
}
return left+ans;
}
};
本文介绍了一种算法,用于计算给定由'('和')'组成的字符串中,最少需要添加多少个括号使字符串变为合法。合法字符串需满足空串、可分解为两个合法子串或可视为合法子串的包裹形式。

3074

被折叠的 条评论
为什么被折叠?



