Check for balanced parentheses in an expression

PROBLEM :

Given an expression string exp, examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the program should print 'balanced' for exp = “[()]{}{[()()]()}” and 'not balanced' for exp = “[(])”



Input:

The first line of input contains an integer T denoting the number of test cases.
Each test case consist of a string of expression, in a separate line.

Output:

Print 'balanced' without quotes if pair of parenthesis are balanced else print 'not balanced' in a separate line.


Constraints:

1 = T = 30
1 = |s| = 100


Example:

Input:
3
{([])}
()
()[]

Output:
balanced
balanced
balanced

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<string.h>

typedef struct STACK
{
    char data ;
    struct STACK *next ;
}stack ;

void push_stack(stack **,char ) ;
char pop_stack(stack **) ;
int compare(char,char ) ;

int main()
 {
int t,no,i,flag,k,len ;
char ch[100],ele ;
cin>>t ;
while(t--)
{
   cin>>ch ;
   len=strlen(ch) ;
 
 
   stack *s=NULL ;
   flag=1 ;
   for(i=0;i<len;i++)
   {
       if((ch[i]=='[')||(ch[i]=='{')||(ch[i]=='('))
           push_stack(&s,ch[i]) ;
         
       else if((ch[i]==']')||(ch[i]=='}')||(ch[i]==')'))
       {
           ele=pop_stack(&s) ;
           if(ele=='#')
           {
               flag=0 ;
               break ;
           }
         
           k=compare(ele,ch[i]) ;
           if(k==0)
           {
               flag=0 ;
               break ;
           }
       }
   }
    if(s!=NULL)
           flag=0 ;
         
    if(flag==0)
       cout<<"not balanced" ;
    else
       cout<<"balanced" ;
     
      cout<<endl ;
}
return 0;
}

void push_stack(stack **s,char ch)
{
    stack *temp ;
    temp=(stack*)malloc(sizeof(stack)) ;
    temp->data=ch ;

    temp->next=(*s) ;
    (*s)=temp ;
}

char pop_stack(stack **s)
{
    stack *temp ;
    if((*s)==NULL)
        return '#' ;
       
    temp=(*s) ;
    (*s)=temp->next ;
    char ch=temp->data ;
    free(temp) ;
    return ch ;
}

int compare(char ch1,char ch2)
{
    if((ch1=='[')&&(ch2==']'))
        return 1 ;
    else if((ch1=='{')&&(ch2=='}'))
        return 1 ;
    else if((ch1=='(')&&(ch2==')'))
        return 1 ;
       
    return 0 ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )