Tuesday, September 27, 2016

Uva 673 - Parentheses Balance Solution

Problem link-click here

This problem can't be solved without using the stack. there's a built-in library function of stack in C++. try google for the syntax of stack library or see the below code to understand the use of stack.

an accepted code is as follows:

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

int main()
{
    int t;

    scanf("%d",&t);
    cin.ignore();

    while(t--)
    {
        string str;

        getline(cin,str);

        stack<char> stk;

        for(int i=0;i<str.length();i++)
        {
            if(!stk.empty() && str[i]==')' && stk.top()=='(')
            {
                stk.pop();
            }
            else if(!stk.empty() && str[i]==']' && stk.top()=='[')
            {
               stk.pop();
            }
            else
            {
                stk.push(str[i]);
            }
        }

        if(stk.empty())
        {
            cout<<"Yes"<<endl;
        }
        else
        {
            cout<<"No"<<endl;
        }
    }

    return 0;
}

No comments:

Post a Comment