« Minimum brackets reversal

For a given expression in the form of a string, find the minimum number of brackets that can be reversed in order to make the expression balanced. The expression will only contain curly brackets.

If the expression can't be balanced, return -1.

Example:

Expression: {{{{

If we reverse the second and the fourth opening brackets, the whole expression will get balanced. Since we have to reverse two brackets to make the expression balanced, the expected output will be 2.

Expression: {{{

In this example, even if we reverse the last opening bracket, we would be left with the first opening bracket and hence will not be able to make the expression balanced and the output will be -1.

Input Format :

The first and the only line of input contains a string expression, without any spaces in between.

Output Format :

The only line of output will print the number of reversals required to balance the whole expression. Prints -1, otherwise.

Constraints:

0 <= N <= 10^6 Where N is the length of the expression.

Time Limit: 1sec

Sample Input 1:

{{{

Sample Output 1:

-1

Sample Input 2:

{{{{}}

Sample Output 2:

1

1#include <iostream>
2#include <string>
3#include <stack>
4#include <cmath>
5
6using namespace std;
7
8int countBracketReversals(string input) {
9 // Write your code here
10 int len = input.length();
11 if(len % 2 != 0){
12 return -1;
13 }
14 stack<int> st;
15 for(int i=0; i<input.length(); i++){
16 if(input[i] == '{'){
17 st.push(input[i]);
18 }else if(input[i] == '}'){
19 if(!st.empty() && st.top() == '{'){
20 st.pop();
21 }else{
22 st.push(input[i]);
23 }
24 }
25 }
26 float x=0;
27 float y=0;
28 while(!st.empty()){
29 if(st.top() == '}'){
30 x++;
31 }else{
32 y++;
33 }
34 st.pop();
35 }
36 return (ceil(x/2) + ceil(y/2));
37}
38
39int main() {
40 string input;
41 cin >> input;
42 cout << countBracketReversals(input);
43}