673 - Parentheses Balance

Post here if you don't find any other place for your post. But please, stay on-topic: algorithms, programming or something related to this web site and its services.

Moderator: Board moderators

Post Reply
nazmulislam
New poster
Posts: 1
Joined: Wed Apr 27, 2016 3:52 pm
Location: savar,dhaka
Contact:

673 - Parentheses Balance

Post by nazmulislam »

Getting Run Time Error
plz help

Code: Select all

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

int main()
{
    long long t;
    char s[1000];
    cin>>t;
    getchar();

    while(t--)
    {
        gets(s);
        stack<char>mystack;
        long long i,j,flag=0,l=strlen(s);
        if(l==0) flag=1;
        for(i=0; i<l; i++)
        {
            if(s[i]=='('||s[i]=='[')
            {
                mystack.push(s[i]);
            }

            if(s[i]==')'&&mystack.top()=='('||s[i]==']'&&mystack.top()=='[')
            {
                mystack.pop();
            }

            if(mystack.empty()&&i==l-1)
            {
                flag=1;
            }
        }
        if(flag==1)
        {
            cout<<"Yes"<<endl;
        }
        else
            cout<<"No"<<endl;
    }
    return 0;
}

lighted
Guru
Posts: 587
Joined: Wed Jun 11, 2014 9:56 pm
Location: Kyrgyzstan, Bishkek

Re: 673 - Parentheses Balance

Post by lighted »

Your code gets RE for the second case of sample input. It happens on the last ')' closing bracket. Because it tries to access the top element of the stack when stack is empty. You should check if stack actually contains anything and then access the top element.
A person who sees the good in things has good thoughts. And he who has good thoughts receives pleasure from life... Bediuzzaman
Post Reply

Return to “Other words”