Friday, November 27, 2020

Redundant Braces | Amazon | InterviewBit | Solution | C++


Problem :

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.


Solution:

 int Solution::braces(string A) {

    // create a stack

    stack<char>s;

    

    // process string char by char

    int l  = A.length();

    for(int i =0;i<l;i++){

        char c = A[i];

        // if c is ( or operator or operand , we push in s

        if(c == '(' || (c >= 'a' && c<='z') || c == '+'||c=='-'||c=='*'||c=='/'){

            s.push(c);

        }

        else{

            // else 

        

        // pop unless we get opening bracket and check the length of popped elements

        // if it is > 1

        //else end processing and it is redundant

        

            // (a + b) -> 5

            

        int p = 0;

        

        while(s.empty() == false && s.top()!='('){

            p++;

            s.pop();

        }     

        s.pop();

        if(p>1)continue;

        else{

            return 1;

        }

    

    }

    

}

return 0;

}





No comments:

Post a Comment