UVA 673 Parentheses Balance






#include <bits/stdc++.h>
using namespace std;
int main()
{
    stack<char>st;
    char s[10000];
    long long int r,c,p,i,j,n;
    cin>>n;
    cin.ignore();
    for(j=1;j<=n;j++)
    {
        r=1;
        gets(s);

        for(i=0;i<=strlen(s);i++)
        {

            if(s[i]=='(' || s[i]=='{' || s[i]=='[')
            {
                st.push(s[i]);
            }

            else if(s[i]==')' || s[i]=='}' || s[i]==']')
            {
                if(st.empty())
                {
                    r=0;
                }
                else
                {
                    p=st.top();
                    if(s[i]==')' && p=='(' || s[i]=='}' && p=='{' || s[i]==']' && p=='[')
                    {
                        st.pop();
                    }
                    else
                    {
                        r=0;
                    }
                }
            }
        }
        if(!st.empty())
        {
            r=0;
        }
        if(r==1)
        {
            cout<<"Yes"<<endl;
        }
        else
        {
            cout<<"No"<<endl;
        }
        while(!st.empty())
        {
            st.pop();
        }
    }

    return 0;
}

Download Coding Interview Book and Get More Tutorials for Coding and Interview Solution: Click Here

Download System Design Interview Book and Get More Tutorials and Interview Solution: Click Here

Do you need more Guidance or Help? Then Book 1:1 Quick Call with Me: Click Here

Share on Google Plus

About Ashadullah Shawon

I am Ashadullah Shawon. I am a Software Engineer. I studied Computer Science and Engineering (CSE) at RUET. I Like To Share Knowledge. Learn More: Click Here
    Blogger Comment
    Facebook Comment

1 comments:

  1. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. mybalancenow.company

    ReplyDelete