Saturday 23 July 2016

Check Balanced Brackets in a string !!


#include <iostream>
using namespace std;

int s1[10000],top=-1;
void push(int t)
    {
    s1[++top]=t;
}
char pop()
    {
    char x=s1[top--];
    return x;
}
int main(){
    int i,t,f=0;
    cin >> t;
    char x;
       string s;
    for(int a0 = 0; a0 < t; a0++){
         f=0;
        cin >> s;
        top=-1;
    for( i=0;i<s.length();i++)
        {
        if(s[i]=='{'||s[i]=='['||s[i]=='(')
            push(s[i]);
        else{
            
            if(s[i]=='}')
                {
                 x=pop();
                if(x!='{')
                    {
                    f=1;
                    break;
                }
                
            }
            else if(s[i]==']')
                {
                 x=pop();
                if(x!='[')
                    {
                    f=1;
                    break;
                }
            }
            else {
                 x=pop();
         
                if(x!='(')
                    {
                    f=1;
                    break;
                
            }
        }
    }
    }
    if(f==1||(top!=-1))
        cout<<"NO\n";
    else
        cout<<"YES\n";
    }
    
    return 0;
}

No comments:

Post a Comment