Check redundant brackets
Expression: (a+b)+c
Since there are no needless brackets, hence, the output must be 'false'.
Expression: ((a+b))
The expression can be reduced to (a+b). Hence the expression has redundant brackets and the output will be 'true'.
You will not get a partial score for this problem. You will get marks only if all the test cases are passed.
The first and the only line of input contains a string expression, without any spaces in between.
The first and the only line of output will print either 'true' or 'false'(without the quotes) denoting whether the input expression contains redundant brackets or not.
You are not required to print the expected result. It has already been taken care of.
0 <= N <= 10^6
Where N is the length of the expression.
Time Limit: 1 second
a+(b)+c
true
The expression can be reduced to a+b+c. Hence, the brackets are redundant.
(a+b)
false
#include<stack>bool checkRedundantBrackets(string ex) { // Write your code here stack <char> s; int count; for(int i=0;ex[i]!='\0';i++){ if(ex[i]==')') { count=0; while(s.top()!='(') { count++; s.pop(); } s.pop(); if(count<2) return true; } else s.push(ex[i]); } return false;}
Comments
Post a Comment