Thursday, April 5, 2018

UVa problem 673 - Parentheses Balance

problem link:

Discuss: This problem i want to solve by counting parentheses before  i know stack. since i know i just laugh at myself. if you know stack then it is just implementation problem for you.there no tricky part in this problem

try yourself before see the code



#include<bits/stdc++.h>
using namespace std;
int main()
{
    //freopen("input.txt","r",stdin);
    // freopen("out.txt","w",stdout);
    int n,i,j,cnt,flag,len;
    cin >>n;
    scanf("\n");
    while(n--)
    {
        flag=0;
        stack<char>stk;
        char str[250];
        gets(str);
        len=strlen(str);
        // cout <<len<<endl;
        for(i=0; i<len; i++)
        {
            if(str[i]=='('||str[i]=='[')
            {
                stk.push(str[i]);
            }
            else if(str[i]==')')
            {
                if(!stk.empty()&&stk.top()=='(')
                {
                    stk.pop();

                }
                else
                {
                    flag=1;
                    break;
                }

            }

            else   if(str[i]==']')
            {
                if(!stk.empty()&&stk.top()=='[')
                {
                    stk.pop();

                }
                else
                {
                    flag=1;
                    break;
                }
            }
        }
        if(stk.empty()&&flag==0||len==0)
            cout <<"Yes"<<endl;
        else
            cout <<"No"<<endl;
    }
    return 0;
}

No comments:

Post a Comment