Minimum bracket Reversal
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.
The first and the only line of input contains a string expression, without any spaces in between.
The only line of output will print the number of reversals required to balance the whole expression. Prints -1, otherwise.
You don't have to print anything. It has already been taken care of.
0 <= N <= 10^6
Where N is the length of the expression.
Time Limit: 1sec
{{{
-1
{{{{}}
1
// int countBracketReversals(string input) {// // Write your code here// }
#include<stack>int countBracketReversals(string input){ stack<char> bracket; for(int i = 0; i < input.size(); i++){ if(input[i] == '{'){ bracket.push(input[i]); } else{ if(!bracket.empty() && bracket.top() != '}'){ bracket.pop(); } else{ bracket.push(input[i]); } } } int count = 0; while (!bracket.empty()){ char c1 = bracket.top(); bracket.pop(); if(bracket.empty()){ return -1; } char c2 = bracket.top(); bracket.pop(); if((c1 == '{' && c2 == '{') || (c1 == '}' && c2 == '}')){ count += 1; } else{ count += 2; } } return count;}
Comments
Post a Comment