Problem Statement

Given a string A denoting an expression. It contains the following operators ’+’, ‘-‘, ‘*’, ‘/’.

Chech whether A has redundant braces or not.

Return 1 if A has redundant braces, else return 0.

Note: A will be always a valid expression.

Input Format

The only argument given is string A.

Output Format

Return 1 if string has redundant braces, else return 0.

For Example

`Input 1: A = "((a + b))" Output 1: 1 Explanation 1: ((a + b)) has redundant braces so answer will be 1.

Input 2: A = "(a + (a + b))" Output 2: 0 Explanation 2: (a + (a + b)) doesn't have have any redundant braces so answer will be 0.`

Problem Link

Redundant Braces - InterviewBit

Code

int Solution::braces(string A) {

    int n = A.size();

    stack<char> s;

    for(char ch:A)
    {
        if(s.empty()||ch!=')')
        s.push(ch);

        else
        {
            bool operatorPoped = false; //if during poping no operator is found then the case may be like (a)
            //where 'a' is surrounded by redundent braces or 
            //if immediate s.top() is '(' then the case may be ((a+b)) where the second ')'
            //has immediate top of stack as '('
            while(s.size()&&s.top()!='(')
            {
                if(s.top()=='+'||s.top()=='*'||s.top()=='-'||s.top()=='/')
                operatorPoped = true;

                
                s.pop();
                
                
            }
            if(!operatorPoped)//if redundent braces found
            return 1;

            s.pop();//else pop '('
        }

        
    }

    return 0;
}