Balanced Parenthesis in a Stack

 Let us check for equal number of parenthesis in a given string. For this we will be using the following algorithm->

  • Declare a character stack S
  • Traverse the expression, If character is {, [, ( bracket, push it in stack
  • If it is },], ) then pop it from stack
  • after completion if there are any brackets then they are unbalanced

function-->

bool check(string str)
{
    stack<char> s;
    char x;

    for(int i =0;i<str.length(), i++)
        if(str[i]=='{' || str[i]=='(' || str[i]== '[')
                s.push(str[i]);
                continue;
    
if(s.empty())
      return false;

switch(str[i])
    case ')' : 
                    x=s.top();
                    s.pop();        
                    if(x=='{' || x=='[')
                        return false;
                     break;
    case '}':
                    x=s.top();
                    s.pop();
                    if(x=='[' || x=='(')
                        return false;
                    break;
    case ']' :
                    x=s.top();
                    s.pop();
                    if(x=='{' || x=='(')
                        return false;
                    break;

return(s.empty())

Popular posts from this blog

Finding the Subarrays (Hackerearth)

Palindrome Index (Hackerrank)

Sherlock and Array (Hackerrank)