7. Minimal additions to make brackets effective

Problem description:
Given a string S consisting of'(' and')' parentheses, we need to add the least amount of parentheses ('(' or')', which can be in any position), to make the resulting string of parentheses effective.
Formally speaking, a parenthesized string is valid only if one of the following is satisfied:
it is an empty string, or
it can be written as AB (A and B are connected), where A and B are both valid strings , Or
it can be written as (A), where A is a valid string.
Given a string of parentheses, return the minimum number of parentheses that must be added 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

Explanation:
S.length <= 1000
S only contains'(' and')' characters.

Input description:
input a string S consisting of'(' and')' brackets

Output description:
output an integer, representing the minimum number of parentheses that must be added to make the result string valid

Input example:
()))((
Output example:
4

/*
给定一个由 '(' 和 ')' 括号组成的字符串 S,我们需要添加最少的括号( '(' 或是 ')',可以在任何位置),以使得到的括号字符串有效。
从形式上讲,只有满足下面几点之一,括号字符串才是有效的:
它是一个空字符串,或者
它可以被写成 AB (A 与 B 连接), 其中 A 和 B 都是有效字符串,或者
它可以被写作 (A),其中 A 是有效字符串。
给定一个括号字符串,返回为使结果字符串有效而必须添加的最少括号数。

 示例 1:
输入:"())"
输出:1

示例 2:
输入:"((("
输出:3

示例 3:
输入:"()"
输出:0

示例 4:
输入:"()))(("
输出:4
*/

#include<iostream>
#include<string>
#include<stack>
using namespace std;

class Solution {
    
    
public:
    int minAddToMakeValid(string S) {
    
    
		stack<char> sc;
		for(int i = 0; i < S.length(); i++) {
    
    
			if(sc.empty()) {
    
    
				sc.push(S[i]);
			}
			else {
    
    
				if(S[i] == ')' && sc.top() == '(') {
    
    
					sc.pop();
				}
				else {
    
    
					sc.push(S[i])
				}
			}
		}
		return sc.size();
    }
};

int main(void) {
    
    
	string str;
	cin>>str;
	
	Solution s;
	int res = s.minAddToMakeValid(str); 
	cout<<res;
	return 0; 
}

Guess you like

Origin blog.csdn.net/qq_37924213/article/details/108571992