Easy cpp approach


#1

APPROACH :-

  1. if length of string is odd than return false.
    2.maintain a stack and start traversing the string if we encounter a opening bracket ‘(’ push it in the stack.
  2. if we enecounter a closing bracket ‘)’ than check with the stack if the size of stack == 0
    return false else pop the top element.
  3. keep doing so for the rest of charcters
  4. when the loop ends , if the string is balanced than stack would be empty
    so check is stack is empty return true else return false;

CODE :-
int Solution::solve(string A)
{
stack s;

int len = A.length();
if(len%2 > 0)
{
    return 0;
}

int i = 0;
while(i < len)
{
    if(A[i] == '(')
    {
        s.push('(');
    }
    else
    {
        if(s.size() == 0)
        {
            return 0;
        }
        else
        {    s.pop();
        }
    }
    i++;
}

if(s.size() == 0)
{
    return 1;
}
else
{
    return 0;
}

}